Python中的文件对象是什么类型?

24 投票
4 回答
29173 浏览
提问于 2025-04-18 11:40

我该如何使用 isinstance 来判断一个文件对象的“类型”,比如在下面这个表达式中:

>>> open(file)

4 个回答

0

它的类型是 file。你可以通过运行 type(open("file","w")) 这个命令来查看。

1

open函数的文档中提到:

打开一个文件,并返回一个file类型的对象,这个类型在文件对象的部分有描述。

所以,open函数会返回一个file对象,你可以用isinstance(foo, file)来检查。

11

你可以根据自己的需要选择合适的 IO 类别。这个回答是基于用户 user2555451 的之前的回答和评论。最后会有一个简单的总结。

对于文本文件,可以使用 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.BufferedReaderio.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

29

在Python 3.x中,普通的文件对象属于一种叫做 io.TextIOWrapper 的类型:

>>> type(open('file.txt'))
<class '_io.TextIOWrapper'>

>>> from io import TextIOWrapper
>>> isinstance(open('file.txt'), TextIOWrapper)
True

而在Python 2.x中,所有的文件对象都是一种叫做 file 的类型:

>>> type(open('file.txt'))
<type 'file'>

>>> isinstance(open('file.txt'), file)
True

撰写回答