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

我已经搜索过了,只能找到关于其他方面的问题: 将 stdin 写入文件。

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

132939 次浏览
f = open('file.txt', 'r')
print f.read()
f.close()

From 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 ("").

Sure. Assuming you have a string with the file's name called fname, the following does the trick.

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

If it's a large file and you don't want to consume a ton of memory as might happen with Ben's solution, the extra code in

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

also works.

You can try this.

txt = <file_path>
txt_opn = open(txt)
print txt_opn.read()

This will give you file output.

you can also try this

print ''.join(file('example.txt'))

My shortened version in Python3

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

If you need to do this with the pathlib module, you can use pathlib.Path.open() to open the file and print the text from read():

from pathlib import Path


fpath = Path("somefile.txt")


with fpath.open() as f:
print(f.read())

Or simply call pathlib.Path.read_text():

from pathlib import Path


fpath = Path("somefile.txt")


print(fpath.read_text())

To improve on @bgporter's answer, with Python-3 you will probably want to operate on bytes instead of needlessly converting things to utf-8:

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

If you are on jupyter notebook, you can simply use:

!cat /path/to/filename

Operating on the file's line iterator (if you open in text mode -- the default) is simple and memory-efficient:

with open(path, mode="rt") as f:
for line in f:
print(line, end="")

Note the end="" because the lines will include their line-ending char(s).

This is almost exactly one of the examples in the docs linked at (other) Ben's answer: https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

do:

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())

or install my ultimate-utils library from pypi.