Get Extension of File in Python

To Get Extension of File in Python, you can use built-in modules like os or pathlib. Extracting file extensions is important for tasks like file type validation, which ensures only certain file types are processed. It’s also crucial in automation scripts and data processing where different actions are taken based on file type, such as reading text files or extracting data from CSVs.

Prerequisites

To follow along, you should have a basic understanding of Python syntax and concepts, especially working with variables and functions. Additionally, a basic understanding of file systems and directories will help you navigate file paths and understand how files are structured, enabling effective manipulation of file extensions.

Python Program to Get an Extension of File Using splittext()

# Python Program to Get an Extension of File Using splittext()

# importing os module
import os

# this will return a tuple of root and extension
split_tup = os.path.splitext('file.txt')
print(split_tup)

# extract the file name and extension
file_name = split_tup[0]
file_extension = split_tup[1]

print("File Name: ", file_name)
print("File Extension: ", file_extension)

Explanation of Code

In this Python program, we use the os.path.splitext() function from the os module to extract the extension of a file. The function splits a given file path into two parts: the root (file name without the extension) and the extension (file type, such as .txt).

  1. os.path.splitext('file.txt'):
    The splitext() function is called with 'file.txt' as the argument. It returns a tuple containing two elements: 'file' (the root) and '.txt' (the extension).
  2. file_name = split_tup[0]:
    This line extracts the file name ('file') from the tuple.
  3. file_extension = split_tup[1]:
    This extracts the file extension ('.txt') from the tuple.

Finally, the file name and extension are printed separately using print() statements.

Output:

('file', '.txt')
File Name:  file
File Extension:  .txt

Python Program to Get an Extension of File Using pathlib

# Python Program to Get an Extension of File Using pathlib

# importing pathlib module
import pathlib

# function to return the file extension
file_extension = pathlib.Path('test.txt').suffix
print("File Extension: ", file_extension)

Explanation of Code

In this Python program, we use the pathlib module to extract the extension of a file. Here’s a step-by-step breakdown:

  1. Importing pathlib:
    We begin by importing the pathlib module, which provides classes to handle and manipulate file system paths in an object-oriented way.
  2. Creating a Path object:
    pathlib.Path('test.txt') creates a Path object representing the file named test.txt. This object allows us to perform various operations on the file path.
  3. Getting the File Extension:
    The .suffix attribute of the Path object is used to retrieve the file extension. In this case, it returns the string .txt, representing the file extension of test.txt.
  4. Printing the File Extension:
    Finally, the program prints the file extension using the print() function. The output will be:
    File Extension: .txt

This approach is simple and effective, offering a modern, object-oriented method for working with file paths in Python.

Output:

File Extension:  .txt

Conclusion

In this blog, we explored different methods to get the extension of a file in Python, including os.path.splitext() and pathlib.Path.suffix. Both approaches are efficient, with os being great for quick scripts and pathlib offering a cleaner, object-oriented solution ideal for modern Python projects.

Choose the method that best suits your coding style and project requirements. For more Python tips, tutorials, and coding insights, explore Newtum’s website and take your skills to the next level.

About The Author

Leave a Reply