user2471451
user2471451

Reputation: 1

Python open document

I am currently biulding a project in the language python which can open text documents (.txt). However I have come across a problem. I tried to open the document by using the following code:

f = open("music_data.txt","r")
print(f)

But it's not working. It just says:

<_io.TextIOWrapper name='music_data.txt' mode='r' encoding='cp1252'>

Which seems to be the standared thing for printing a variable containing a document, but then it gives an error message:

Traceback (most recent call last):
File "\\bcs\StudentRedir2010$\StudentFiles\MyName\MyDocuments\Computing\Programming\Python\Music Program\program.py", line 45, in <module>
mode()
File "\\bcs\StudentRedir2010$\StudentFiles\MyName\MyDocuments\Computing\Programming\Python\Music Program\program.py", line 43, in mode
mode()
TypeError: 'str' object is not callable

And I don't know why this is.

Upvotes: 0

Views: 2502

Answers (4)

Srikanth Parimi
Srikanth Parimi

Reputation: 1

Try the following, it should work:

f = open("music_data.txt","r")
print f.read()

Upvotes: 0

Charitoo
Charitoo

Reputation: 1872

f is a file object i.e sort of a reference to the file that contains other information and not just the contents. There are several way to access the contents of the file.

1. Iterate over contents

for line in f:
    # process line

The behaviour can sometimes not be what you want. If the file consists of more than one line it will iterate over the lines. If the file contains one line, it iterates over the characters

2. Use readline()

f is an instance of io.TextWrapper which has a readline method. It reads and returns chars until a newline is encountered. There is a newline argument for the open function. To read words from the document you could do this: open(path/to/file, mode, newline=" ")

3. Use read()

Reads and returns chars until EOF is encountered.

4. Use readlines()

Read and returns a list of lines from the file

Upvotes: 0

msturdy
msturdy

Reputation: 10794

Check out the "with" pattern for working with files, as it handles closing the file nicely as well, even in cases where exceptions cause the halting of the script:

with open("your-file.txt", "r") as my_file:
  file_contents = my_file.read()
  print(file_contents)

more info in the python docs

Upvotes: 1

Nick Peterson
Nick Peterson

Reputation: 771

f is not the contents of the file - it is a file object. You can print the entire contents of the file using print(f.read()); you can also iterate through it line by line (much more memory efficient):

for line in f:
    print(line)  # or do whatever else you want with the line...

You can find more at the Python Tutorial page on files.

Upvotes: 4

Related Questions