我有一个路径:删除最后一个路径组件在一个字符串
myPath = "C:\Users\myFile.txt"
我想,这样的字符串只包含删除结束路径:
"C:\Users"
到目前为止,我使用的分裂,但它只是给了我一个清单,而且我坚持在这一点上。
myPath = myPath.split(os.sep)
我有一个路径:删除最后一个路径组件在一个字符串
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:\
像这样。
但是,这只有当该路径不结束与一个“/” – Awsed 2015-09-17 13:07:17
您还可以使用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'
这应该是'myPath',不'fPath' – ghostdog74 2010-07-23 02:56:26