How to Read from Stdin in Python

Created
Modified

Using fileinput Module

This module implements a helper class and functions to quickly write a loop over standard input or a list of files. For example,

#!/usr/bin/python3

# Import module
import fileinput

for line in fileinput.input(encoding="utf-8"):
    # process(input)
    pass
abc

Note that this will include a newline character at the end. To remove the newline at the end, use line.rstrip().

Using sys.stdin

stdin is used for all interactive input.

See the following example:

#!/usr/bin/python3

# Import module
import sys

for line in sys.stdin:
    # process(input)
    pass
abc

Using input Function

The function reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:

#!/usr/bin/python3

s = input('--> ')
print(s)
--> abc
abc

Related Tags

#read# #stdin#