Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if an object is a file with isinstance()?

How can I check if an object is a file?

>>> f = open("locus.txt", "r")
>>> type(f)
<class '_io.TextIOWrapper'>
>>> isinstance(f, TextIOWrapper)
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    isinstance(f, TextIOWrapper)
NameError: name 'TextIOWrapper' is not defined
>>> isinstance(f, _io.TextIOWrapper)
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    isinstance(f, _io.TextIOWrapper)
NameError: name '_io' is not defined
>>> isinstance(f, _io)
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    isinstance(f, _io)
NameError: name '_io' is not defined
>>> 

I have the variable f that is a text file. When I print the type of f the Python3 interpreter shows '_io.TextIOWrapper', but if I check it with isinstance() function throws exception: NameError.

like image 382
Trimax Avatar asked Apr 09 '14 09:04

Trimax


People also ask

How do you check if an object is a file in Python?

We use the is_file() function, which is part of the Path class from the pathlib module, or exists() function, which is part of the os. path module, in order to check if a file exists or not in Python.

How do you check if an object is a certain class Python?

Using isinstance() function, we can test whether an object/variable is an instance of the specified type or class such as int or list. In the case of inheritance, we can checks if the specified class is the parent class of an object. For example, isinstance(x, int) to check if x is an instance of a class int .

What can the Isinstance function be used for?

The isinstance() function can be used to check the data type of the specified object matches the specified class. It states that when we pass an object and classinfo to the isinstance function, this function compares the object's class with the classinfo class(es).

Should I use Isinstance or type?

isinstance is usually the preferred way to compare types. It's not only faster but also considers inheritance, which is often the desired behavior. In Python, you usually want to check if a given object behaves like a string or a list, not necessarily if it's exactly a string.


1 Answers

_io is the C implementation for the io module. Use io.IOBase for direct subclasses, after importing the module:

>>> import io
>>> f = open("tests.py", "r")
>>> isinstance(f, io.IOBase)
True
like image 193
Martijn Pieters Avatar answered Sep 27 '22 22:09

Martijn Pieters