read from stdin in python

How to Read from Stdin in Python

Sometimes you may need to read input from stdin in Python. In this article, we will learn some of the easy ways to do this. This is not a typical software requirement but may come up in programming contests and interviews. So it is good to know.

How to Read from Stdin in Python

Here are the different ways to read from stdin in Python.

1. Using sys.stdin

One of the simplest ways to read from stdin is using sys.stdin

import sys

for line in sys.stdin:

The above code, when run, will keep accepting input from stdin and printing it immediately. It will also include newline character. If you don’t want to include newline character, you can use rstrip() function as shown below.

import sys

for line in sys.stdin:

2. Using fileinput

You can also use fileinput module for this purpose.

import fileinput

for line in fileinput.input():

When you run the above script, the above code will loop through all lines in input, specified as file names, given as command line argument, or standard input if no argument is given.

The main difference between these above functions and input() function in python is that the above functions allow you to read multiple lines or file contents, whereas input() function allows you to read only one line.

In this article, we have learnt a couple of simple ways to read from standard input in Python.

Also read:

How to Download Large Files in Python Requests
How to Remove All Occurrences of Item in List
How to Move File in Python
How to Reset Auto Increment in MySQL
How to Show Last Queries Executed in MySQL

Leave a Reply

Your email address will not be published.