How Do I Get the Filename without the Extension from a Path in Python?
Better Stack Team
Updated on June 19, 2024
You can get the filename without the extension from a path in Python using the os.path module. Here's how you can do it:
In this code:
os.path.basename(file_path)returns the last component of the path, which is the filename ('file.txt' in this example).os.path.splitext()splits the filename into its base name and extension. It returns a tuple where the first element is the base name and the second element is the extension ('.txt' in this example).[0]at the end of the expression accesses the first element of the tuple, which is the base name without the extension ('file' in this example).