Read Input From Stdin in Python

To read input from stdin in Python, import the fileinput package and use the .input() method.

 

To demonstrate this, let's open, VIA the command line, a sample .txt file containing some content and print each line.

 

sample.txt
A line of text.
Another line of text.
import fileinput

for line in fileinput.input():
   print(line.rstrip())
python read_file.py "sample.txt"
A line of text.
Another line of text.

 

In the above example, .rstrip() used to remove trailing newline statements from the output.

 

Stdin to Python List

If you need to use the data from stdin somewhere in your program outside of the for loop, append each line to a Python list like this:

 

import fileinput

data = []
for line in fileinput.input():
   data.append(line.rstrip())