Two Methods To Check Whether An Object Is A File Object In Python Or Not

File manipulation is a common scenario in development, so how to judge whether an object is a file object or not? Here we summarise two methods .

1. Compare Object Type.

The first method is to determine whether the object type is file or not.But this method does not apply to sub classes inherited from file.

# open a file object in python
>>> fp = open("/tmp/test.png", 'r')
# get the object type value and print the value in console
>>> type(fp)
<type 'file'>
# compare above value with file, if the result is true then the object is a file.
>>> type(fp) == file
True

In below python source code we can not use above code to check file class’s sub class type to be a file.

# define a new class extends from file class.
class subFile(file):
     ......
# create a new object of above sub class. 
fp2 = subFile("/tmp/tmp.png", 'r')

# get sub class instance object type
fileType = type(fp2)

# print the type to console
print(fileType)

Run above code we get below result.

<class '__main__.subFile'>

2. Use isinstance Method.

To determine whether an object is a file object, you can use isinstance() directly. In the following code, the fp object returned by open function is file, of course fp is an instance of file, while the filename’s type is string, which is naturally not an instance of file.

>> filename = r"/tmp/pythontab.com"
>>> type(filename)
<type 'str'>
>>> isinstance(filename, file)
False
fp = open(filename, 'r') 
>>> isinstance(fp, file)
True

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.