How do get Python to print the contents of a file [duplicate]

I'm trying to get Python to print the contents of a file:

log = open("/path/to/my/file.txt", "r") print str(log) 

Gives me the output:

<open file '/path/to/my/file.txt', mode 'r' at 0x7fd37f969390> 

Instead of printing the file. The file just has one short string of text in it, and when I do the opposite (writing the user_input from my Python script to that same file) it works properly.

edit: I see what Python thinks I'm asking it, I'm just wondering what the command to print something from inside a file is.

2

4 Answers

It is better to handle this with "with" to close the descriptor automatically for you. This will work with both 2.7 and python 3.

with open('/path/to/my/file.txt', 'r') as f: print(f.read()) 

open gives you an iterator that doesn't automatically load the whole file at once. It iterates by line so you can write a loop like so:

for line in log: print(line) 

If all you want to do is print the contents of the file to screen, you can use print(log.read())

open() will actually open a file object for you to read. If your intention is to read the complete contents of the file into the log variable then you should use read()

log = open("/path/to/my/file.txt", "r").read() print log 

That will print out the contents of the file.

file_o=open("/path/to/my/file.txt") //creates an object file_o to access the file content=file_o.read() //file is read using the created object print(content) //print-out the contents of file file_o.close() 

You Might Also Like