[英]How to print a file to stdout?
我已经搜索过,我只能找到关于另一种方式的问题:将标准输入写入文件。
有没有一种快速简便的方法可以将文件内容转储到stdout
?
当然。 假设你有一个名为fname
的文件名的字符串,下面的方法就可以了。
with open(fname, 'r') as fin:
print(fin.read())
如果它是一个大文件,并且您不想像 Ben 的解决方案那样消耗大量内存,则在
>>> import shutil
>>> import sys
>>> with open("test.txt", "r") as f:
... shutil.copyfileobj(f, sys.stdout)
也有效。
f = open('file.txt', 'r')
print f.read()
f.close()
来自http://docs.python.org/tutorial/inputoutput.html
要读取文件的内容,请调用 f.read(size),它读取一定数量的数据并将其作为字符串返回。 size 是一个可选的数字参数。 当 size 省略或为负时,将读取并返回文件的全部内容; 如果文件是机器内存的两倍大,那是你的问题。 否则,最多读取和返回 size 个字节。 如果已到达文件末尾, f.read() 将返回一个空字符串 ("")。
我在 Python3 中的缩短版本
print(open('file.txt').read())
你也可以试试这个
print ''.join(file('example.txt'))
你可以试试这个。
txt = <file_path>
txt_opn = open(txt)
print txt_opn.read()
这将为您提供文件输出。
如果您需要使用pathlib
模块执行此pathlib
,您可以使用pathlib.Path.open()
打开文件并从read()
打印文本:
from pathlib import Path
fpath = Path("somefile.txt")
with fpath.open() as f:
print(f.read())
或者简单地调用pathlib.Path.read_text()
:
from pathlib import Path
fpath = Path("somefile.txt")
print(fpath.read_text())
为了改进@bgporter 的答案,使用 Python-3,您可能希望对字节进行操作,而不是不必要地将内容转换为 utf-8:
>>> import shutil
>>> import sys
>>> with open("test.txt", "rb") as f:
... shutil.copyfileobj(f, sys.stdout.buffer)
如果您使用的是jupyter notebook
,则只需使用:
!cat /path/to/filename
对文件的行迭代器进行操作(如果您以文本模式打开——默认)很简单且节省内存:
with open(path, mode="rt") as f:
for line in f:
print(line, end="")
注意end=""
因为这些行将包含它们的行尾字符。
这几乎正是(其他)Ben 回答中链接的文档中的示例之一: https : //docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects
做:
def expanduser(path: Union[str, Path]):
"""
note: if you give in a path no need to get the output of this function because it mutates path. If you
give a string you do need to assign the output to a new variable
:param path:
:return:
"""
if not isinstance(path, Path):
# path: Path = Path(path).expanduser()
path: Path = Path(path).expanduser()
path = path.expanduser()
assert not '~' in str(path), f'Path username was not expanded properly see path: {path=}'
return path
def cat_file(path2filename: Union[str, Path]):
"""prints/displays file contents. Do path / filename or the like outside of this function. ~ is alright to use. """
path2filename = expanduser(path2filename)
with open(path2filename, 'r') as f:
print(f.read())
或者从 pypi 安装我的 Ultimate-utils 库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.