我该如何使用isinstance
来确定文件对象的“类型”,例如在这个表达式中:
>>> open(file)
我该如何使用isinstance
来确定文件对象的“类型”,例如在这个表达式中:
>>> open(file)
io.TextIOWrapper
:>>> type(open('file.txt'))
<class '_io.TextIOWrapper'>
>>> from io import TextIOWrapper
>>> isinstance(open('file.txt'), TextIOWrapper)
True
file
类型的:>>> type(open('file.txt'))
<type 'file'>
>>> isinstance(open('file.txt'), file)
True
read
方法或write
方法,或者其他一些与文件接口相关的特性。通常你应该检查这些特性,方法是尝试使用这个对象像读写文件一样,如果它不支持你需要的接口则捕获错误。 - user2357112open('file.txt', 'rb')
会得到类型为<class '_io.BufferedReader'>
的结果。 - RickTextIOWrapper
,如果以二进制('b')模式打开,则会返回BufferedReader
。因此,您可以单独检查它们,或者如果想要捕获两者,可以使用它们的超类IOBase
。 - AndrewWhalanio.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
总之,我通常会选择io.TextIOBase
来处理文本文件,io.BufferedIOBase
来处理二进制文件,以及io.IOBase
来处理不特定文件。
它的类型是file
。你可以通过type(open("file","w"))
的输出来确定。
typing
模块中的TextIO
(例如在“前言”中使用from typing import TextIO
,然后在代码中使用file_handle: TextIO = open(...)
)。请注意不要改变原文意思。 - mutableVoid