Skip to content
Related Articles

Related Articles

Take input from stdin in Python

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 09 Sep, 2022
View Discussion
Improve Article
Save Article

In this article, we will read How to take input from stdin in Python.

There are a number of ways in which we can take input from stdin in Python.

Read Input From stdin in Python using sys.stdin

First we need to import sys module. sys.stdin can be used to get input from the command line directly. It used is for standard input. It internally calls the input() method. Furthermore, it, also, automatically adds ‘\n’ after each sentence.

Example: Taking input using sys.stdin in a for-loop

Python3




import sys
 
for line in sys.stdin:
    if 'q' == line.rstrip():
        break
    print(f'Input : {line}')
 
print("Exit")

Output 

 

Read Input From stdin in Python using input()

The input() can be used to take input from the user while executing the program and also in the middle of the execution.

Python3




# this accepts the user's input
# and stores in inp
inp = input("Type anything")
 
# prints inp
print(inp)

Output:

 

Read Input From stdin in Python using fileinput.input()

If we want to read more than one file at a time, we use fileinput.input(). There are two ways to use fileinput.input(). To use this method, first, we need to import fileinput.

Example 1: Reading multiple files by providing file names in fileinput.input() function argument

Here, we pass the name of the files as a tuple in the “files” argument. Then we loop over each file to read it. “sample.txt” and “no.txt” are two files present in the same directory as the Python file.

Python3




import fileinput
 
with fileinput.input(files=('sample.txt', 'no.txt')) as f:
    for line in f:
        print(line)

Output: 

 

Example 2: Reading multiple files by passing file names from command line using fileinput module

Here, we pass the file name as a positional argument in the command line. fileargument parses the argument and reads the file and displays the content of the file.

Python3




import fileinput
 
for f in fileinput.input():
    print(f)

Output: 

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!