因为文件不能在python 3中使用。
在python 2中,我们判断文件类型可以做到这一点:
with open("xxx.txt") as f:
if isinstance(f, file):
print("ok!")在python 3中,我们可以这样做:
import io
with open("xxx.txt") as f:
if isinstance(f, io.IOBase)
print("ok!")但是第二段代码不能在python 2中工作。
那么,是否有一种方法可以判断python 2和python 3中的文件类型。
发布于 2014-09-09 07:09:59
您可以使用tuple来测试这两种情况;使用NameError保护程序在Python3上进行测试:
import io
try:
filetypes = (io.IOBase, file)
except NameError:
filetypes = io.IOBase
isinstance(f, filetypes)您需要在Python2上进行测试,因为您也可以在那里使用io库。
但是,最好是使用鸭子类型,而不是对io.IOBase进行测试;有关动机,请参见Check if object is file-like in Python。最好检查您需要的方法是否存在:
if hasattr(f, 'read'):请注意,io.IOBase甚至不包括read。在Python2中,StringIO.StringIO也是一个类似文件的对象,isinstance(.., file)不支持它。
https://stackoverflow.com/questions/25738602
复制相似问题