Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Taking input in Python
Next article icon

In this article, we will readHow 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.stdincan 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
importsysforlineinsys.stdin:if'q'==line.rstrip():breakprint(f'Input :{line}')print("Exit")

Output 

 

Read Input From stdin in Python using input()

Theinput() 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 inpinp=input("Type anything")# prints inpprint(inp)

Output:

 

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

If we want to read more than one file at a time, we usefileinput.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
importfileinputwithfileinput.input(files=('sample.txt','no.txt'))asf:forlineinf: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
importfileinputforfinfileinput.input():print(f)

Output: 

 

Improve

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp