[英]What type are file objects in Python?
如何使用isinstance
确定文件对象的“类型”,例如在表达式中:
>>> open(file)
在 Python 2.x 中,所有文件对象都是file
类型:
>>> type(open('file.txt'))
<type 'file'>
>>> isinstance(open('file.txt'), file)
True
然而,在 Python 3.x 中,普通文件对象的类型为io.TextIOWrapper
:
>>> type(open('file.txt'))
<class '_io.TextIOWrapper'>
>>> from io import TextIOWrapper
>>> isinstance(open('file.txt'), TextIOWrapper)
True
它的类型是file
。 您可以通过type(open("file","w"))
的输出来判断
该答案建立在 user2555451 的先前答案及其评论的基础上。 简短的回答是从IO 类层次结构中选择您的偏好。
对于文本文件,可以接受io.TextIOBase
:
>>> import io
>>> type(f := open('/tmp/foo', 'w'))
<class '_io.TextIOWrapper'>
>>> isinstance(f, io.TextIOBase)
True
>>> f.__class__.__bases__
(<class '_io._TextIOBase'>,)
>>> f.__class__.__mro__
(<class '_io.TextIOWrapper'>, <class '_io._TextIOBase'>, <class '_io._IOBase'>, <class 'object'>)
对于文本文件,请避免io.TextIOWrapper
,因为它也不适用于io.StringIO
:
>>> isinstance(io.StringIO('foo'), io.TextIOWrapper)
False
>>> isinstance(io.StringIO('foo'), io.TextIOBase)
True
对于二进制文件,可以接受io.BufferedIOBase
:
>>> import io
>>> type(f := open('/tmp/foo', 'wb'))
<class '_io.BufferedWriter'>
>>> isinstance(f, io.BufferedIOBase)
True
>>> f.__class__.__bases__
(<class '_io._BufferedIOBase'>,)
>>> f.__class__.__mro__
(<class '_io.BufferedWriter'>, <class '_io._BufferedIOBase'>, <class '_io._IOBase'>, <class 'object'>)
对于二进制文件,请避免io.BufferedReader
或io.BufferedWriter
,因为它们也不适用于io.BytesIO
:
>>> isinstance(io.BytesIO(b'foo'), io.BufferedReader)
False
>>> isinstance(io.BytesIO(b'foo'), io.BufferedWriter)
False
>>> isinstance(io.BytesIO(b'foo'), io.BufferedIOBase)
True
为了同时支持文本和二进制文件, io.IOBase
是可以接受的:
>>> import io
>>> isinstance(open('/tmp/foo', 'w'), io.IOBase)
True
>>> isinstance(open('/tmp/foo', 'wb'), io.IOBase)
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.