Check if object is file-like in Python

Viewed 63502

File-like objects are objects in Python that behave like a real file, e.g. have a read() and a write method(), but have a different implementation from file. It is realization of the Duck Typing concept.

It is considered a good practice to allow a file-like object everywhere where a file is expected so that e.g. a StringIO or a Socket object can be used instead a real file. So it is bad to perform a check like this:

if not isinstance(fp, file):
   raise something

What is the best way to check if an object (e.g. a parameter of a method) is "file-like"?

9 Answers

try this:

import os 

if os.path.isfile(path):
   'do something'
Related