How to get file extension in Python?

Published on Aug. 22, 2023, 12:15 p.m.

It looks like you may have accidentally included search results for a different question in your response. Nonetheless, here’s how you can get file extension from a file path in Python:

To get the file extension from a file path in Python , you can use the os.path.splitext() function. This function splits the file path into a tuple having two values - the file path and the file extension. You can then access the file extension by selecting the second element of the tuple. For example:

import os

file_path = "/path/to/file.txt"
file_extension = os.path.splitext(file_path)[1]

print(file_extension) # Output: .txt

In this example, we define a file path file_path and use os.path.splitext() to split the path into a tuple having two values. We then select the second element of the tuple to get the file extension and store the result in the variable file_extension. Finally, we print out the file extension to the console.

Note that the file extension includes the leading period (.). If you want to get the file extension without the period, you can use string slicing to remove it.

To traverse a directory in Python and filter files based on their extension

To traverse a directory in Python and filter files based on their extension, you can use the os module and a list comprehension. Here’s an example:

import os

dir_path = '/path/to/directory'
extension = '.txt'

files = [f for f in os.listdir(dir_path) if f.endswith(extension)]

print(files)

In this example, we define a directory path dir_path and an extension extension (in this case, “.txt”). We then use a list comprehension to iterate through all files in the directory and select only those that end with the specified extension. The resulting list of selected files is stored in the files variable and printed to the console.

You can modify the code to choose a different directory and file extension by changing the values of dir_path and extension.

Tags:

os