'How to print 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?
Solution 1:[1]
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.
Solution 2:[2]
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 ("").
Solution 3:[3]
My shortened version in Python3
print(open('file.txt').read())
Solution 4:[4]
you can also try this
print ''.join(file('example.txt'))
Solution 5:[5]
You can try this.
txt = <file_path>
txt_opn = open(txt)
print txt_opn.read()
This will give you file output.
Solution 6:[6]
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())
Solution 7:[7]
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)
Solution 8:[8]
If you are on jupyter notebook, you can simply use:
!cat /path/to/filename
Solution 9:[9]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | bgporter |
| Solution 2 | Ben |
| Solution 3 | mlanzero |
| Solution 4 | Ninja420 |
| Solution 5 | Shoaib |
| Solution 6 | RoadRunner |
| Solution 7 | mricon |
| Solution 8 | Ali Hassaine |
| Solution 9 |
