How do I get the filename without the extension from a path in Python?
To get the filename without the extension from a file path in Python, you can use the os.path.splitext()
function. This function returns a tuple containing the file name and the file extension. You can then use string slicing to get just the file name.
Here's an example:
import os
file_path = '/path/to/file.txt'
# Use os.path.splitext to split the file name and extension
filename, file_ext = os.path.splitext(file_path)
# Use slicing to get the file name without the extension
filename_without_ext = filename[:-len(file_ext)]
print(filename_without_ext) # Output: '/path/to/file'
Watch a video course
Python - The Practical Guide
Alternatively, you can use the os.path.basename()
function to get the base name of the file, and then use string slicing to remove the extension. Here's an example:
import os
file_path = '/path/to/file.txt'
# Get the base name of the file
filename = os.path.basename(file_path)
# Use slicing to remove the extension
filename_without_ext = filename[:filename.rindex('.')]
print(filename_without_ext) # Output: 'file'
Both of these methods assume that the file extension is separated from the rest of the file name by a period (.
). If this is not the case, then you will need to use a different approach to split the file name and extension.