Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python command isn't reading a .txt file

Tags:

python

text

Trying to follow the guide here, but it's not working as expected. I'm sure I'm missing something.

http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files

file = open("C:/Test.txt", "r");
print file
file.read()
file.read()
file.read()
file.read()
file.read()
file.read()

Using the readline() method gives the same results.

file.readline() 

The output I get is:

<open file 'C:/Test.txt', mode 'r' at 0x012A5A18>

Any suggestions on what might be wrong?


2 Answers

Nothing's wrong there. file is an object, which you are printing.

Try this:

file = open('C:/Test.txt', 'r')
for line in file.readlines(): print line,
like image 188
Frank Avatar answered May 26 '26 10:05

Frank


print file invokes the file object's __repr__() function, which in this case is defined to return just what is printed. To print the file's contents, you must read() the contents into a variable (or pass it directly to print). Also, file is a built-in type in Python, and by using file as a variable name, you shadow the built-in, which is almost certainly not what you want. What you want is this:

infile = open('C:/test.txt', 'r')
print infile.read()
infile.close()

Or

infile = open('C:/test.txt', 'r')
file_contents = infile.read()
print file_contents
infile.close()
like image 29
Chinmay Kanchi Avatar answered May 26 '26 10:05

Chinmay Kanchi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!