路径名称的递归拆分(Python)?
我觉得应该有一个Python函数,可以递归地把一个路径字符串拆分成它里面的文件和目录(不仅仅是获取文件名和目录名)。我自己写了一个,但因为我在五台以上的电脑上用Python做脚本,所以我希望能找到一个标准库里的或者更简单的函数,方便随时使用。
import os
def recsplit(x):
if type(x) is str: return recsplit(os.path.split(x))
else: return (x[0]=='' or x[0] == '.' or x[0]=='/') and x[1:] or \
recsplit(os.path.split(x[0]) + x[1:])
>>> print recsplit('main/sub1/sub2/sub3/file')
('main', 'sub1', 'sub2', 'sub3', 'file')
有没有什么线索或者想法呢?~谢谢~
3 个回答
在编程中,有时候我们需要让程序在特定的条件下执行某些操作。比如说,当某个变量的值达到一定的标准时,我们就希望程序能做出反应。这种情况通常会用到“条件语句”。
条件语句就像是一个判断的开关,它会根据你设定的条件来决定接下来要做什么。如果条件满足,程序就会执行某些代码;如果不满足,程序可能会执行其他的代码,或者什么都不做。
举个简单的例子,想象一下你在家里有一个灯开关。你可以设定一个条件,比如“如果外面天黑了,就打开灯”。在这个例子中,天黑就是条件,打开灯就是程序要执行的操作。
在编程中,条件语句的写法可能会有点复杂,但它的核心思想就是这样简单。只要你理解了这个基本概念,就能更好地使用条件语句来控制程序的行为。
path='main/sub1/sub2/sub3/file'
path.split(os.path.sep)
使用这个:
import os
def recSplitPath(path):
elements = []
while ((path != '/') and (path != '')):
path, tail = os.path.split(path)
elements.insert(0,tail)
return elements
这样可以把 /for/bar/whatever
转换成 ['for','bar','whatever']
更新:经过一番折腾,当前选中的答案甚至没有在反斜杠上进行分割。
>>> import re, os.path
>>> seps = os.path.sep
>>> if os.path.altsep:
... seps += os.path.altsep
...
>>> seps
'\\/'
>>> somepath = r"C:\foo/bar.txt"
>>> print re.split('[%s]' % (seps,), somepath)
['C:\\foo', 'bar.txt'] # Whoops!! it was splitting using [\/] same as [/]
>>> print re.split('[%r]' % (seps,), somepath)
['C:', 'foo', 'bar.txt'] # after fixing it
>>> print re.split('[%r]' % seps, somepath)
['C:', 'foo', 'bar.txt'] # removed redundant cruft
>>>
现在回到我们应该做的事情:
(更新结束)
1. 仔细考虑你想要什么——你可能得到的是你想要的,而不是你需要的。
如果你有相对路径
r"./foo/bar.txt"
(在unix系统上)和r"C:foo\bar.txt"
(在windows系统上)
你想要的是
[".", "foo", "bar.txt"]
(在unix上)和["C:foo", "bar.txt"]
(在windows上)
(注意这里的C:foo)还是想要
["", "CWD", "foo", "bar.txt"]
(在unix上)和["C:", "CWD", "foo", "bar.txt"]
(在windows上)
其中CWD是当前工作目录(在unix上是系统范围的,在windows上是C:的目录)?
2. 你不需要纠结于os.path.altsep
——使用os.path.normpath()
可以统一分隔符,并整理其他奇怪的路径,比如foo/bar/zot/../../whoopsy/daisy/somewhere/else
解决步骤1:用os.path.normpath()
或os.path.abspath()
来整理你的路径。
步骤2:直接用unkinked_path.split(os.path.sep)
并不是个好主意。你应该先用os.path.splitdrive()
分离驱动器,然后多次使用os.path.split()
来拆分路径。
以下是在windows上步骤1的示例:
>>> os.path.abspath(r"C:/hello\world.txt")
'C:\\hello\\world.txt'
>>> os.path.abspath(r"C:hello\world.txt")
'C:\\Documents and Settings\\sjm_2\\hello\\world.txt'
>>> os.path.abspath(r"/hello\world.txt")
'C:\\hello\\world.txt'
>>> os.path.abspath(r"hello\world.txt")
'C:\\Documents and Settings\\sjm_2\\hello\\world.txt'
>>> os.path.abspath(r"e:hello\world.txt")
'E:\\emoh_ruo\\hello\\world.txt'
>>>
(当前驱动器是C
,C驱动器上的当前工作目录是\Documents and Settings\sjm_2
,E驱动器上的当前工作目录是\emoh_ruo
)
我建议你在步骤2中不要像你例子里那样把and
和or
混在一起。写代码的时候就像你的最终替代者知道你住在哪里并且手里拿着电锯一样 :-)