How to print a file to stdout?

Question:

I’ve searched and I can only find questions about the other way around: writing stdin to a file.

Is there a quick and easy way to dump the contents of a file to stdout?

Asked By: meteoritepanama

||

Answers:

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 (“”).

Answered By: Ben

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())
Answered By: David Alber

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.

Answered By: bgporter

You can try this.

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

This will give you file output.

Answered By: Shoaib

you can also try this

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

Answered By: Ninja420

My shortened version in Python3

print(open('file.txt').read())
Answered By: mlanzero

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())
Answered By: RoadRunner

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)
Answered By: mricon

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

!cat /path/to/filename
Answered By: Ali Hassaine

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

Answered By: Ben Mosher
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.