打开文件时出现python TextIOWrapper问题

2024-10-05 14:25:51 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么我在尝试读取一个简单的文本文件时会得到这个输出

MT = open("MT.fasta")
print(MT)    

<_io.TextIOWrapper name='MT.fasta' mode='r' encoding='cp1252'>

每隔一次它都会给我文件的内容,但现在它会返回attibutes。已经尝试关闭重新启动Spyder,但仍然得到相同的结果

还试图关闭并重新打开文件本身,但没有成功

MT.close()

我怎样才能解决这个问题


Tags: 文件nameio内容modeopenencodingfasta
3条回答
print(MT.read())

将打印文件的内容

python中的文件具有读取、写入它们的方法

这里有一个很好的指南:

https://www.programiz.com/python-programming/file-operation

MT是一个对象,您应该使用它方法read()来显示文本

MT = open("MT.fasta", "r")
print(MT.read())

因为MT是实际的文件(一个TextIOWrapper对象),而不是它的内容。您可以使用该对象的read方法(即MT.read())或其他替代方法从该对象获取内容,具体取决于您的应用程序,例如我使用最多的^{}。您可以在官方Python documentation中找到更多方法。另请注意:

It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try-finally blocks:

with open('workfile') as f:
    read_data = f.read()

相关问题 更多 >