簡體   English   中英

Python中的文件對象是什么類型的?

[英]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

open文檔中所述

打開一個文件,返回文件對象部分中描述的file類型的對象

因此, open返回一個file ,你應該使用isinstance(foo, file)

它的類型是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.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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM