fileinput.filename() method in Python

In this tutorial, we will be learning about the fileinput.filename() method in Python. This method is used to get the name of the file that is currently being read by fileinput.input() method. We will see some examples further in this post to explain it better.

The syntax for fileinput.filename() is given as follows:

fileinput.filename()

And it returns the name of the file which has been most recently used by fileinput.input() method and not yet closed.

Example of fileinput.filename() method in Python

Have a look at the given example and its output.

import fileinput 

for line in fileinput.input(files = "codespeedy.txt"): 
  print(line) 

print("\nName of the file currently being read is: ", fileinput.filename()) 

Output:

CodeSpeedy

CodeSpeedy

Name of the file currently being read is: codespeedy.txt

The file codespeedy.txt has two lines with each line as ‘CodeSpeedy’. We read the file using fileinput.input() method, then we print the name of the file using fileinput.filename() method.

When we read more than one file with fileinput.input() method, the fileinput.filename() method returns the most recently used file. You can notice that in the next example. See the code.

import fileinput 

for line in fileinput.input(files = ("codespeedy.txt", "code.txt")): 
  print(line) 

print("\nName of the file currently being read is: ", fileinput.filename()) 

Output:

CodeSpeedy

CodeSpeedy
code

code

Name of the file currently being read is: code.txt

In the above program, we read two text files using filename.input() method. Since the code.txt is the most recent file to be used, the filename() method returns code.txt as output.

Now, Have a look at the below Python code.

import fileinput 

for line in fileinput.input(files = "code.txt"): 
  print(line) 
    
fileinput.close()

print(fileinput.filename()) 

Output:

code

code
Traceback (most recent call last):
File "ac.py", line 8, in <module>
print(fileinput.filename())
File "C:\Users\Ranjeet Verma\Anaconda3\lib\fileinput.py", line 125, in filename
raise RuntimeError("no active input()")
RuntimeError: no active input()

The above code reads the file code.txt as you can see in the output and then it throws an error. That is because we are using the filename() method after we have closed the files using fileinput.close().

Thank you.

Also read: Python File Handling

Leave a Reply

Your email address will not be published. Required fields are marked *