关于Python中的路径问题
假设我有一些目录路径,像这样:
this/is/the/basedir/path/a/include
this/is/the/basedir/path/b/include
this/is/the/basedir/path/a
this/is/the/basedir/path/b
在Python中,我该如何把这些路径拆分成这样:
a/include
b/include
a
b
如果我运行 os.path.split(path)[1],它会显示:
include
include
a
b
我应该尝试什么呢?我需要用到一些正则表达式的命令吗,还是可以不用它就能做到?提前谢谢大家。
编辑:我用正则表达式解决了这个问题,真是个好工具 :)
4 个回答
1
也许可以这样做:
result = []
prefix = os.path.commonprefix(list_of_paths)
for path in list_of_paths:
result.append(os.path.relpath(path, prefix))
这个方法只在2.6版本中有效。在2.5及之前的版本中,relapath这个功能只有在路径是当前工作目录时才会起作用。
1
那关于 partition 呢?
这个方法会在字符串中找到第一次出现的分隔符,然后把字符串分成三部分,分别是分隔符前的内容、分隔符本身,以及分隔符后的内容。如果找不到分隔符,就会返回一个包含整个字符串和两个空字符串的三元组。
data = """this/is/the/basedir/path/a/include
this/is/the/basedir/path/b/include
this/is/the/basedir/path/a
this/is/the/basedir/path/b"""
for line in data.splitlines():
print line.partition("this/is/the/basedir/path/")[2]
#output
a/include
b/include
a
b
根据作者的新评论更新:
看起来你需要使用 rsplit 来处理不同的目录,具体取决于目录是否以 "include" 结尾:
import os.path
data = """this/is/the/basedir/path/a/include
this/is/the/basedir/path/b/include
this/is/the/basedir/path/a
this/is/the/basedir/path/b"""
for line in data.splitlines():
if line.endswith('include'):
print '/'.join(line.rsplit("/",2)[-2:])
else:
print os.path.split(line)[1]
#or just
# print line.rsplit("/",1)[-1]
#output
a/include
b/include
a
b
3
也许可以这样做,这要看你的前缀是多么固定:
def removePrefix(path, prefix):
plist = path.split(os.sep)
pflist = prefix.split(os.sep)
rest = plist[len(pflist):]
return os.path.join(*rest)
用法:
print removePrefix("this/is/the/basedir/path/b/include", "this/is/the/basedir/path")
b/include
假设你使用的平台的目录分隔符(os.sep
)确实是正斜杠。
这段代码试图把路径处理得比单纯的字符串更高级一点。不过,这样做并不是最优的,你可以(或者应该)做更多的清理和标准化,以确保更安全。