Movatterモバイル変換


[0]ホーム

URL:


Open In App

With the help of fileinput.input() method, we can get the file as input and can be used to update and append the data in the file by usingfileinput.input() method.

Python fileinput.input() Syntax

Syntax :fileinput.input(files)

Parameter :

Return : Return the data of the file.

What is fileinput.input() in Python?

`fileinput.input()` inPython is a function provided by the `fileinput` module. It allows reading input from multiple files. The function returns an iterable, and the optional `files` parameter specifies the files to read from; if not provided, it defaults to reading from standard input (stdin). Each iteration of the iterable corresponds to a line from the specified files.

Python fileinput.input() Examples

There are various methods to open a file by user input inPython here, we are discussing some general use cases of opening a file by user input in Python which are the following.

Reading From a Single File

Input File

In this example we can see that by usingfileinput.input()method, we are able to get the data of the file line by line by using this method.

Python3
importfileinputfilename='example.txt'forlineinfileinput.input(files=filename):print(line,end='')

Output :

Reading From Multiple Files

Input Files

In this example code utilizes thefileinput module in Python to read input from the specified files, 'gfg.txt' and 'gfg1.txt'. Thefileinput.input() method returns an iterable, and the loop iterates over each line from the files, printing them to the console

Python3
# import fileinputimportfileinput# Using fileinput.input() methodforlineinfileinput.input(files=('gfg.txt','gfg1.txt')):print(line)

Output


Improve

Explore

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