从字符串中移除最后一个路径组件
我有一个路径:
myPath = "C:\Users\myFile.txt"
我想把这个路径的结尾部分去掉,这样字符串里只剩下:
"C:\Users"
到目前为止,我用的是分割的方法,但它只给我一个列表,我在这一步卡住了。
myPath = myPath.split(os.sep)
4 个回答
22
现在的做法是使用Python标准库里的pathlib
模块,这个模块在Python 3.4及以上版本都可以用。
>>> 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
这个模块还有一个好处,就是它可以在不同的操作系统上都能正常工作。比如说,我现在用的是Windows 10,pathlib
会自动生成适合这个系统的路径对象。
还有一些其他有用的属性和方法:
path.name
>> "myFile.txt"
path.stem
>> "myFile"
path.parts
>> ("C:\\", "Users", "myFile.txt")
path.with_suffix(".csv")
>> "myFile.csv"
path.iterdir()
>> #iterates over all files/directories in path location
path.isdir()
>> #tells you if path is file or directory
50
你还可以使用 os.path.split
,用法如下:
>>> import os
>>> os.path.split('product/bin/client')
('product/bin', 'client')
这个方法会把一个路径分成两部分,并把这两部分放在一个元组里返回。你可以把这些值分别放到变量里,然后再使用它们,像这样:
>>> head, tail = os.path.split('product/bin/client')
>>> head
'product/bin'
>>> tail
'client'
146
你不应该直接处理路径,应该使用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:\
就像这样。