How do I get the filename without the extension from a path in Python? "/path/to/some/file.txt" → "file"

 

To get the filename without the extension from a path in Python, you can use the os.path.basename() function to extract the filename and then use string manipulation to remove the extension. Here's an example:

python
import os # Example path file_path = "/path/to/some/file.txt" # Get the filename with extension filename_with_extension = os.path.basename(file_path) # Get the filename without extension filename_without_extension = os.path.splitext(filename_with_extension)[0] print(filename_without_extension) # Output: "file"

In this example:

  1. We import the os module, which provides functions for working with file paths.

  2. We specify the file_path variable with your example path, "/path/to/some/file.txt."

  3. We use os.path.basename(file_path) to extract the filename with the extension. In this case, it will be "file.txt."

  4. We use os.path.splitext(filename_with_extension)[0] to split the filename into its base name and extension, and then select the base name (index 0). This gives us "file" as the result.

The filename_without_extension variable will contain the filename without the extension, which is "file" in this case.

Comments