Is there a function to extract the extension from a filename?

 

Yes, you can extract the file extension from a filename in Python using the os.path.splitext() function. This function is part of the os module and separates the filename into its root and extension components. Here's how to use it with an example:

python
import os # Example filename filename = "example.txt" # Use os.path.splitext() to extract the extension root, extension = os.path.splitext(filename) # Print the results print("Filename:", filename) print("Root:", root) print("Extension:", extension)

In this example:

  • We import the os module, which provides operating system-related functionality.

  • We define an example filename, "example.txt."

  • We use the os.path.splitext() function to split the filename into two parts: the root and the extension. The function returns a tuple containing both parts.

  • We print the original filename, the root part (without the extension), and the extension.

When you run this code, it will output:

makefile
Filename: example.txt Root: example Extension: .txt

This way, you can easily extract the file extension from a filename in Python using the os.path.splitext() function.

Comments