python TextIOWrapper problem when opening a file

Why I am getting this output when trying to read a simple text file?

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

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

Every other time it gave me the contents of the file, but now it returns attibutes. Already tried closing an reopnening Spyder, but keep getting the same result.

Also tried to close and reopen the file itself, but to no avail

MT.close()

How can I fix this?

Answer

Because MT is the actual file (a TextIOWrapper object), not its contents. You can get the contents from that object using its read method (i.e. MT.read()) or other alternatives depending on your application, e.g. readlines, which I use the most. You can find more methods in the official Python documentation. Also note:

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()

Leave a Reply

Your email address will not be published. Required fields are marked *