如何将文件打印到标准输出?

104

我已经搜索了,但只找到关于另一种方式的问题:将stdin写入文件。

是否有一种快速简便的方法将文件内容转储到stdout


你可以从这里插入我的函数:https://dev59.com/02sz5IYBdhLWcg3wJUjJ#73336009 - Charlie Parker
11个回答

140

当然可以。假设您有一个名为 fname 的包含文件名的字符串,以下代码可以实现您想要的效果。

with open(fname, 'r') as fin:
    print(fin.read())

10
请注意,这将在输出末尾添加一个额外的换行符。 - D. A.
16
为了兼容Python 3并避免输出末尾的换行符,最后一行应该这样写:print(fin.read(), end="")。如果想在 Python 2 中使用这种解决方案,需要在开头加上 from __future__ import print_function 前缀。当然,Python 2 应用程序应该始终使用 Python 3 的 print() 函数 - 这不是很麻烦。 - Cecil Curry

45

如果文件很大,而且你不想像Ben的解决方案那样消耗大量的内存,可以使用下面的代码:

>>> import shutil
>>> import sys
>>> with open("test.txt", "r") as f:
...    shutil.copyfileobj(f, sys.stdout)
同样有效。

18
f = open('file.txt', 'r')
print f.read()
f.close()

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

想要读取一个文件的内容,可以调用f.read(size)函数,该函数会读取一定量的数据并返回一个字符串。其中size是可选的数字参数。当省略或为负数时,将读取整个文件的内容并返回;如果文件大小是机器内存的两倍,那将是你的问题。否则,最多读取size字节并返回。如果已经到达文件结尾,f.read()将返回一个空字符串("")。


9

我用Python3编写了一个简化版

print(open('file.txt').read())

6
注意:这不会关闭文件。 - Ben Caine

3
您也可以尝试这个: print ''.join(file('example.txt')) 该代码与读取文本文件相关。

1
如果你需要使用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())

0

做:

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库。


0
你可以试试这个。
txt = <file_path>
txt_opn = open(txt)
print txt_opn.read()

这将为您提供文件输出。


0

如果你在使用 jupyter notebook ,你可以简单地使用以下代码:

!cat /path/to/filename

0

如果你以文本模式打开文件,对文件的行迭代器进行操作是简单且节省内存的:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接