[python] Python: printing a file to stdout

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?

This question is related to python

The answer is


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


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.


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)

you can also try this

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


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

You can try this.

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

This will give you file output.


My shortened version in Python3

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