Reputation: 408
I'm trying to learn to manipulate files on python, but I can't get the open function to work. I have made a .txt file called foo that holds the content "hello world!" in my user directory (/home/yonatan) and typed this line into the shell:
open('/home/yonatan/foo.txt')
What i get in return is:
<_io.TextIOWrapper name='/home/yonatan/foo.txt' mode='r' encoding='UTF-8'>
I get what that means, but why don't I get the content?
Upvotes: 0
Views: 124
Reputation:
open()
returns a file object.
You then need to use read()
to read the whole file
f = open('/home/yonatan/foo.txt', 'r')
contents = f.read()
Or you can use readline()
to read just one line
line = f.readline()
and don't forget to close the file at the end
f.close()
Upvotes: 3
Reputation: 3525
An example iterating through the lines of the file (using with
which ensures file.close()
gets called on the end of it's lexical scope):
file_path = '/home/yonatan/foo.txt'
with open(file_path) as file:
for line in file:
print line
A great resource on I/O and file handling operations.
Upvotes: 3
Reputation: 43
You haven't specified the mode you want to open it in.
Try:
f = open("home/yonatan/foo.txt", "r")
print(f.read())
Upvotes: -4