簡體   English   中英

isinstance文件python 2.7和3.5

[英]isinstance file python 2.7 and 3.5

在Python 2.7中,我得到以下結果:

>>> with open("README.md", "r") as fin:
...     print(isinstance(fin, file))
... 
True

在python 3.5我得到:

>>> with open("README.md", "r") as fin:
...     print(isinstance(fin, file))
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'file' is not defined

那么,好吧,我看看Python文檔io.IOBase現在Python 3.5中,文件的類型為io.IOBase (或某些子類)。 引導我到這個:

>>> import io
>>> with open("README.md", "r") as fin:
...     print(isinstance(fin, io.IOBase))
... 
True

但是當我在Python 2.7中嘗試時:

>>> import io
>>> with open("README.md", "r") as fin:
...     print(isinstance(fin, io.IOBase))
... 
False

所以在這一點上,我很困惑。 看一下文檔 ,我覺得Python 2.7應該報告True

顯然我錯過了一些基本的東西,也許是因為它是美國東部時間下午6:30,但我有兩個相關的問題:

  1. 為什么Python為isinstance(fin, io.IOBase)報告False isinstance(fin, io.IOBase)
  2. 有沒有辦法測試變量是一個可以在Python 2.7和3.5中運行的打開文件?

從鏈接的文檔:

在Python 2.x下,建議將其作為內置文件對象的替代方案

所以它們在python 2.x中是不一樣的。

至於第2部分,這適用於python2和3,雖然不是世界上最漂亮的東西:

import io
try:
    file_types = (file, io.IOBase)

except NameError:
    file_types = (io.IOBase,)

with open("README.md", "r") as fin:
    print(isinstance(fin, file_types))

對於python2

import types
f = open('test.txt', 'r')   # assuming this file exists
print (isinstance(f,types.FileType))

對於python3

import io
import types
f1 = open('test.txt', 'r')   # assuming this file exists
f2 = open('test.txt', 'rb')   # assuming this file exists
print (isinstance(f1,io.IOBase))
print (isinstance(f2,io.IOBase))

(編輯:我以前的解決方案測試了io.TextIOWrapper,它只適用於以文本模式打開的文件。請參閱https://docs.python.org/3/library/io.html#class-hierarchy ,它描述了python3類層次結構)。

暫無
暫無

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

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