我已经搜索了,但只找到关于另一种方式的问题:将stdin写入文件。
是否有一种快速简便的方法将文件内容转储到stdout
?
我已经搜索了,但只找到关于另一种方式的问题:将stdin写入文件。
是否有一种快速简便的方法将文件内容转储到stdout
?
当然可以。假设您有一个名为 fname
的包含文件名的字符串,以下代码可以实现您想要的效果。
with open(fname, 'r') as fin:
print(fin.read())
print(fin.read(), end="")
。如果想在 Python 2 中使用这种解决方案,需要在开头加上 from __future__ import print_function
前缀。当然,Python 2 应用程序应该始终使用 Python 3 的 print()
函数 - 这不是很麻烦。 - Cecil Curry如果文件很大,而且你不想像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字节并返回。如果已经到达文件结尾,f.read()将返回一个空字符串("")。
我用Python3编写了一个简化版
print(open('file.txt').read())
print ''.join(file('example.txt'))
该代码与读取文本文件相关。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())
做:
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库。
txt = <file_path>
txt_opn = open(txt)
print txt_opn.read()
这将为您提供文件输出。
如果你在使用 jupyter notebook
,你可以简单地使用以下代码:
!cat /path/to/filename
如果你以文本模式打开文件,对文件的行迭代器进行操作是简单且节省内存的:
with open(path, mode="rt") as f:
for line in f:
print(line, end="")
end=""
,因为行将包括它们的行结束字符。