Reputation: 205
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?
Upvotes: 1
Views: 2425
Reputation: 818
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. Usingwith
is also much shorter than writing equivalenttry-finally
blocks:
with open('workfile') as f:
read_data = f.read()
Upvotes: 1
Reputation: 11
MT is an object, and you should use it method read()
to show the text.
MT = open("MT.fasta", "r")
print(MT.read())
Upvotes: 1
Reputation: 305
To read a file using python, use the following syntax:
MT = open("MT.fasta", "r")
print(MT.read())
You can read more about it here
Upvotes: 0
Reputation: 465
print(MT.read())
will print the contents of your file.
files in python have methods to read them, write to them ...
here is a nice guide :
https://www.programiz.com/python-programming/file-operation
Upvotes: 1