Python:将文件打印到stdou

2024-04-27 03:39:07 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

当然。假设您有一个名为fname的字符串,那么下面的操作就完成了。

with open(fname, 'r') as fin:
    print(fin.read())
f = open('file.txt', 'r')
print f.read()
f.close()

http://docs.python.org/tutorial/inputoutput.html

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ("").

如果它是一个大文件,并且您不想像Ben的解决方案那样消耗大量内存,那么

>>> import shutil
>>> import sys
>>> with open("test.txt", "r") as f:
...    shutil.copyfileobj(f, sys.stdout)

同样有效。

相关问题 更多 >