How to Remove the Last Path Component from a String in Python?

Estimated read time 1 min read

To remove the last path component (or directory) from a string in Python, you can use the os.path module, which provides a platform-independent way of working with file paths. Here is an example code snippet that removes the last path component from a string:

import os

original_path = "/path/to/directory/file.txt"

# Remove the last path component from the string
new_path = os.path.dirname(original_path)

print(new_path)  # Output: '/path/to/directory'

In this code, we import the os module to work with file paths.

Next, we define an original path (original_path) that contains a file path with several directories.

Then, we create a new path (new_path) by calling the os.path.dirname() function on the original path. This function returns the directory component of the path.

Finally, we print the new path (new_path) that contains the original path with the last path component (or directory) removed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply