Python: printing a file to stdout
Solution 1:
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())
Solution 2:
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 3:
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 4:
My shortened version in Python3
print(open('file.txt').read())