import os file_name = "example.txt" base, ext = os.path.splitext(file_name) print(ext)
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.
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.