【问题标题】:How to judge a file type both work in python 2 and python 3如何判断文件类型在 python 2 和 python 3 中都有效
【发布时间】:2014-09-09 07:08:30
【问题描述】:

因为文件不能在 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 中都可以工作。

【问题讨论】:

    标签: python file python-2.7 python-3.x isinstance


    【解决方案1】:

    你可以用一个元组来测试两者;使用 NameError 守卫在 Python 3 上进行这项工作:

    import io
    
    try:
        filetypes = (io.IOBase, file)
    except NameError:
        filetypes = io.IOBase
    
    isinstance(f, filetypes)
    

    您需要在 Python 2 上测试两者,因为您也可以在那里使用 io 库。

    但是,最好使用鸭子类型而不是测试io.IOBase;有关动机,请参阅Check if object is file-like in Python。最好检查一下你需要的方法是否存在:

    if hasattr(f, 'read'):
    

    请注意,io.IOBase 甚至不包括 read。在 Python 2 中,StringIO.StringIO 也是一个类似文件的对象,isinstance(.., file) 将不支持。

    【讨论】:

      猜你喜欢
      • 2017-08-26
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多