Open In App

fileinput.input() in Python

Last Updated : 29 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 using fileinput.input() method.

Python fileinput.input() Syntax

Syntax : fileinput.input(files)

Parameter :

  • fileinput module in Python has input() for reading from multiple files.
  • input() in fileinput reads input from various sources.
  • files parameter specifies file names, defaulting to stdin if not specified.

Return : Return the data of the file.

What is fileinput.input() in Python?

`fileinput.input()` in Python 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 in Python 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 using fileinput.input() method, we are able to get the data of the file line by line by using this method.

Python3




import fileinput
 
filename = 'example.txt'
 
for line in fileinput.input(files=filename):
    print(line, end='')


Output :

Reading From Multiple Files

Input Files

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

Python3




# import fileinput
import fileinput
 
# Using fileinput.input() method
for line in fileinput.input(files =('gfg.txt', 'gfg1.txt')):
    print(line)


Output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads