Python 删除字符串中的最后一个路径组件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3315045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove Last Path Component In a String
提问by Brock Woolf
I have a path:
我有一条路径:
myPath = "C:\Users\myFile.txt"
I would like to remove the end path so that the string only contains:
我想删除结束路径,以便字符串只包含:
"C:\Users"
So far I am using split, but it just gives me a list, and im stuck at this point.
到目前为止,我正在使用 split,但它只是给了我一个列表,我在这一点上卡住了。
myPath = myPath.split(os.sep)
采纳答案by Daniel Kluev
You should not manipulate paths directly, there is os.path module for that.
你不应该直接操作路径,有 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:\
Like this.
像这样。
回答by thefourtheye
You can also use os.path.split, like this
你也可以os.path.split像这样使用
>>> import os
>>> os.path.split('product/bin/client')
('product/bin', 'client')
It splits the path into two parts and returns them in a tuple. You can assign the values in variables and then use them, like this
它将路径分成两部分并在元组中返回它们。您可以在变量中分配值,然后使用它们,就像这样
>>> head, tail = os.path.split('product/bin/client')
>>> head
'product/bin'
>>> tail
'client'
回答by johnDanger
The current way to do this (Python > 3.4) is to use the pathlibmodule.
当前执行此操作的方法(Python > 3.4)是使用pathlib模块。
>>> import pathlib
>>> path = pathlib.Path(r"C:\Users\myFile.txt")
>>> path.parent
WindowsPath('C:/Users') #if using a Windows OS
>>> print(path.parent)
C:\Users
This has the additional benefit of being cross platform as pathlibwill make a path object suited for the current operating system (I am using Windows 10)
这具有跨平台的额外好处,因为它pathlib将使路径对象适合当前操作系统(我使用的是 Windows 10)

