young marx
young marx

Reputation: 408

Attempt to use the open() function failing

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

Answers (3)

user2261062
user2261062

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

ospahiu
ospahiu

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

Andrew B
Andrew B

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

Related Questions