簡體   English   中英

如何將文件打印到標准輸出?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM