13

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.

4

4 回答 4

41

最好使用“with”来自动为您关闭描述符。这适用于 2.7 和 python 3。

with open('/path/to/my/file.txt', 'r') as f:
    print(f.read())
于 2013-08-17T18:27:36.287 回答
18

open给你一个迭代器,它不会一次自动加载整个文件。它逐行迭代,因此您可以编写如下循环:

for line in log:
    print(line)

如果您只想将文件的内容打印到屏幕上,您可以使用print(log.read())

于 2013-08-17T18:00:08.977 回答
4

open()实际上会打开一个文件对象供您阅读。如果您打算将文件的完整内容读入日志变量,那么您应该使用read()

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

这将打印出文件的内容。

于 2013-08-17T18:33:10.883 回答
3
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()
于 2013-08-17T19:26:24.293 回答