Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

linux

bash

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.

like image 424
user Avatar asked Aug 17 '13 17:08

user


1 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())
like image 54
lpapp Avatar answered Oct 26 '22 00:10

lpapp