繁体   English   中英

isinstance文件python 2.7和3.5

[英]isinstance file python 2.7 and 3.5

在Python 2.7中,我得到以下结果:

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

在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

那么,好吧,我看看Python文档io.IOBase现在Python 3.5中,文件的类型为io.IOBase (或某些子类)。 引导我到这个:

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

但是当我在Python 2.7中尝试时:

>>> import io
>>> with open("README.md", "r") as fin:
...     print(isinstance(fin, io.IOBase))
... 
False

所以在这一点上,我很困惑。 看一下文档 ,我觉得Python 2.7应该报告True

显然我错过了一些基本的东西,也许是因为它是美国东部时间下午6:30,但我有两个相关的问题:

  1. 为什么Python为isinstance(fin, io.IOBase)报告False isinstance(fin, io.IOBase)
  2. 有没有办法测试变量是一个可以在Python 2.7和3.5中运行的打开文件?

从链接的文档:

在Python 2.x下,建议将其作为内置文件对象的替代方案

所以它们在python 2.x中是不一样的。

至于第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))

对于python2

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

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

(编辑:我以前的解决方案测试了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