How to get the name of an open file?

6    Asked by JamesBuckland in Python , Asked on Jul 10, 2025

This question explores methods in different programming languages (like Python or Java) to access the filename of an open file object, whether for logging, display, or validation.

If you're working with files in your code, it’s common to want the name of the file you’ve opened—maybe for logging, error messages, or just confirming what’s being used. The way you do this depends on the programming language you're using, but it's usually very straightforward.

 In Python:

When you open a file using open(), the file object has a .name attribute that gives you the filename.

file = open('example.txt', 'r')
print(file.name) # Output: example.txt

  • Works for both read and write modes.
  • It only returns the name, not the full path unless that’s what you passed.

 In Java:

If you're using a FileReader or File object, you can get the name using .getName().

File file = new File("example.txt");
System.out.println(file.getName()); // Output: example.txt

Use .getAbsolutePath() if you want the full path instead.

 Why you might need the file name:

  • For debugging/logging
  • User confirmation (e.g., “You uploaded file: example.txt”)
  • File management (moving, renaming, etc.)

So, no matter the language, accessing the name of an open file is usually just a property or method call away. It’s one of those small, helpful tricks that can save you time and make your code more user-friendly!



Your Answer

Interviews

Parent Categories