User Tools

Site Tools


print_file_stdout_using_python

task

Write a python script to display the contents of a file to stdout

solution

You can do

import fileinput

with fileinput.input() as f_input:
    for line in f_input:
        print(line, end='')

If you save this script as filein.py and make it executable, you can do all of the following and get the expected output:

$ ls | ./filein.py          # Prints a directory listing to stdout.
$ ./filein.py /etc/passwd   # Reads /etc/passwd to stdout.
$ ./filein.py < /etc/passwd # Reads /etc/passwd to stdout.

If you want to print the filename and line number along with the contents, you can use

import fileinput

with fileinput.input() as f:
    for line in f:
        print(f.filename(), f.lineno(), line, end='')

Credits:- I found these two tips in Python Cookbook by David Beazley, Brian K Jones, 3rd edition, published in 2013 → Chapter 13 → pg 539-540.

See also:

one liner

python -c "import fileinput; print(''.join(fileinput.input()), end='')"

For example

$ ls | python -c "import fileinput; print(''.join(fileinput.input()), end='')"              # Prints a directory listing to stdout.
$ python -c "import fileinput; print(''.join(fileinput.input()), end='')" /etc/passwd       # Reads /etc/passwd to stdout.
$ python -c "import fileinput; print(''.join(fileinput.input()), end='')" < /etc/passwd     # Reads /etc/passwd to stdout.
print_file_stdout_using_python.txt · Last modified: 2024/10/24 22:11 by raju