从 Python 中的字符串中删除最后一个路径组件

从 Python 中的字符串中删除最后一个路径组件

Remove the last path component from a String in Python

从字符串中删除最后一个路径组件:

  1. 使用pathlib.Path该类创建路径对象。
  2. 访问parent对象的属性。
  3. parent属性返回路径的逻辑父级。
主程序
from pathlib import Path absolute_path = '/home/bobbyhadz/Desktop/python/main.py' result = Path(absolute_path).parent print(result) # 👉️ /home/bobbyhadz/Desktop/python absolute_path = '/home/bobbyhadz/Desktop/' result = Path(absolute_path).parent print(result) # 👉️ /home/bobbyhadz

pathlib.Path
类用于根据您的操作系统创建一个
一个对象PosixPathWindowsPath

parent
属性返回路径的逻辑父级

主程序
from pathlib import Path print(Path('/a/b/c').parent) # 👉️ '/a/b' print(Path('/a/b/c/').parent) # 👉️ '/a/b'

这种方法适用于 POSIX 和 Windows。

或者,您可以使用该os.path.dirname()方法。

Remove the last path component from a String using os.path.dirname() #

To remove the last path component from a string:

  1. Use the os.path.normpath() method to strip any trailing slashes from the
    path.
  2. Use the os.path.dirname() method to remove the last path component.
main.py
import os absolute_path = '/home/bobbyhadz/Desktop/python/main.py' result = os.path.dirname(os.path.normpath(absolute_path)) print(result) # 👉️ /home/bobbyhadz/Desktop/python absolute_path = '/home/bobbyhadz/Desktop/' result = os.path.dirname(os.path.normpath(absolute_path)) print(result) # 👉️ /home/bobbyhadz

The
os.path.normpath
method normalizes a path by removing double slashes and stripping trailing
slashes.

The
os.path.dirname
method returns the directory component of a pathname.

The os.path.dirname() method wouldn’t work if the path ends with a slash.

main.py
import os absolute_path = '/home/bobbyhadz/Desktop/' result = os.path.dirname(absolute_path) print(result) # 👉️ /home/bobbyhadz/Desktop

This is why we had to use the os.path.normpath method to strip any trailing
slashes before calling os.path.dirname.