import os file_name = "example.txt" base, ext = os.path.splitext(file_name) print(ext)
.txt
You can extract the extension from a file name in Python using the os.path module, specifically the os.path.splitext() function. This function splits a file path into a tuple containing the file name and extension.
Alternatively, you can also use the str.rsplit() method to extract the extension. Here's an example:
file_name = "example.txt" ext = file_name.rsplit(".",1)[-1] print(ext) # Prints 'txt'This will split the file name on the last '.' and take the last item of the resulting list.
Both of these methods will return the extension of the file, including the '.' if there is one.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.