find the extension of a file in python

To find the extension of a file in Python, you can use the os module. Here's an example:

main.py
import os

filename = "example.txt"
extension = os.path.splitext(filename)[1]

print(extension)  # output: ".txt"
114 chars
7 lines

The os.path.splitext() function splits the filename at the extension separator and returns a tuple with the base filename and the extension. In this example, we use [1] to extract the second element of the tuple, which is the extension. Note that the extension includes the dot (.) character.

gistlibby LogSnag