Linux 如何让 Python 打印文件的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18291753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do get Python to print the contents of a file
提问by user
I'm trying to get Python to print the contents of a file:
我正在尝试让 Python 打印文件的内容:
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.
而不是打印文件。该文件中只有一个短文本字符串,当我做相反的事情时(将我的 Python 脚本中的 user_input 写入同一个文件),它可以正常工作。
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.
编辑:我知道 Python 认为我在问什么,我只是想知道从文件内部打印内容的命令是什么。
采纳答案by Free Monica Cellio
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:
open
为您提供一个不会立即自动加载整个文件的迭代器。它逐行迭代,因此您可以像这样编写循环:
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())
如果您只想将文件的内容打印到屏幕上,您可以使用 print(log.read())
回答by lpapp
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”处理此问题,以便为您自动关闭描述符。这适用于 2.7 和 python 3。
with open('/path/to/my/file.txt', 'r') as f:
print(f.read())
回答by Oli
open()
will actually open a file objectfor you to read. If your intention is to read the complete contents of the file into the log variable then you should use read()
open()
实际上会打开一个文件对象供您阅读。如果您打算将文件的完整内容读入日志变量,那么您应该使用read()
log = open("/path/to/my/file.txt", "r").read()
print log
That will print out the contents of the file.
这将打印出文件的内容。
回答by rogue_leader
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()