tags:

views:

72

answers:

4

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?

+4  A: 

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,
Frank
Ah so I was doing a .ToString() on an object and not the contents of the object. Thanks! :) When using this for loop to iterate through the contents of the file, I'm getting a space between each row of content, is this normal? The lines in the file itself are stacked with no empty line between them.
Serg
Yes, this is normal, because `print` automatically inserts a newline by default. You can fix this by adding a comma after the `print` statement like `print line,`, which Frank has already done :).
Chinmay Kanchi
Why not simply `for line in file: ...`?
delnan
A: 

You have to read the file first!

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

You can write also:

file = open("C:/Test.txt", "r").read()
print(file)
fif0
+1  A: 
print file.read()
Ashish
+1  A: 

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()
Chinmay Kanchi
Didn't know file was a reserved keyword. Upboated! Thanks for the help.
Serg
It's not a reserved keyword as such, but a built-in type. The difference being that you can't give a variable the same name as a keyword, but you _can_ give it the same name as an existing (built-in or not) type. When you do that, the existing type becomes inaccessible. Python allows you to do some crazy things at times ;). For example: `for = 10` is invalid, because `for` is a keyword, but `int = 10` is perfectly valid. It just means that you can't use the `int` type anymore in that context.
Chinmay Kanchi
+1, thanks for sharing the knowledge.
Serg