我有一条路:
myPath = "C:\Users\myFile.txt"
我想删除结束路径,以便字符串只包含:
"C:\Users"
到目前为止,我正在使用拆分,但它只是给了我一个列表,我卡在这一点上。
myPath = myPath.split(os.sep)
最佳答案
你不应该直接操作路径,有 os.path 模块。
>>> import os.path
>>> print os.path.dirname("C:\Users\myFile.txt")
C:\Users
>>> print os.path.dirname(os.path.dirname("C:\Users\myFile.txt"))
C:\
像这样。
关于python - 删除字符串中的最后一个路径组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3315045/