In Python 2.7 I get the following results:
>>> with open("README.md", "r") as fin:
... print(isinstance(fin, file))
...
True
In python 3.5 I get:
>>> with open("README.md", "r") as fin:
... print(isinstance(fin, file))
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'file' is not defined
So, OK I look at the Python docs and find out that in Python 3.5, files are of type io.IOBase
(or some subclass). Leading me to this:
>>> import io
>>> with open("README.md", "r") as fin:
... print(isinstance(fin, io.IOBase))
...
True
But then when I try in Python 2.7:
>>> import io
>>> with open("README.md", "r") as fin:
... print(isinstance(fin, io.IOBase))
...
False
So at this point, I'm confused. Looking at the documentation, I feel as though Python 2.7 should report True
.
Obviously I'm missing something elementary, perhaps because it's 6:30 PM ET, but I have two related questions:
False
for isinstance(fin, io.IOBase)
?From the linked documentation:
Under Python 2.x, this is proposed as an alternative to the built-in file object
So they are not the same in python 2.x.
As to part 2, this works in python2 and 3, though not the prettiest thing in the world:
import io
try:
file_types = (file, io.IOBase)
except NameError:
file_types = (io.IOBase,)
with open("README.md", "r") as fin:
print(isinstance(fin, file_types))
For python2
import types
f = open('test.txt', 'r') # assuming this file exists
print (isinstance(f,types.FileType))
For python3
import io
import types
f1 = open('test.txt', 'r') # assuming this file exists
f2 = open('test.txt', 'rb') # assuming this file exists
print (isinstance(f1,io.IOBase))
print (isinstance(f2,io.IOBase))
(Edit: my previous solution tested for io.TextIOWrapper, it worked only with files opened in text mode. See https://docs.python.org/3/library/io.html#class-hierarchy which describes the python3 class hierarchy).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With