简体   繁体   English

isinstance文件python 2.7和3.5

[英]isinstance file python 2.7 and 3.5

In Python 2.7 I get the following results: 在Python 2.7中,我得到以下结果:

>>> with open("README.md", "r") as fin:
...     print(isinstance(fin, file))
... 
True

In python 3.5 I get: 在python 3.5我得到:

>>> 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). 那么,好吧,我看看Python文档io.IOBase现在Python 3.5中,文件的类型为io.IOBase (或某些子类)。 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: 但是当我在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 . 看一下文档 ,我觉得Python 2.7应该报告True

Obviously I'm missing something elementary, perhaps because it's 6:30 PM ET, but I have two related questions: 显然我错过了一些基本的东西,也许是因为它是美国东部时间下午6:30,但我有两个相关的问题:

  1. Why does Python report False for isinstance(fin, io.IOBase) ? 为什么Python为isinstance(fin, io.IOBase)报告False isinstance(fin, io.IOBase)
  2. Is there a way to test that a variable is an open file which will work in both Python 2.7 and 3.5? 有没有办法测试变量是一个可以在Python 2.7和3.5中运行的打开文件?

From the linked documentation: 从链接的文档:

Under Python 2.x, this is proposed as an alternative to the built-in file object 在Python 2.x下,建议将其作为内置文件对象的替代方案

So they are not the same in python 2.x. 所以它们在python 2.x中是不一样的。

As to part 2, this works in python2 and 3, though not the prettiest thing in the world: 至于第2部分,这适用于python2和3,虽然不是世界上最漂亮的东西:

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 对于python2

import types
f = open('test.txt', 'r')   # assuming this file exists
print (isinstance(f,types.FileType))

For python3 对于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). (编辑:我以前的解决方案测试了io.TextIOWrapper,它只适用于以文本模式打开的文件。请参阅https://docs.python.org/3/library/io.html#class-hierarchy ,它描述了python3类层次结构)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM