|
需求是酱的:
输入一个目录,这个目录包含检测目录的必备信息但不准确需要获得后加工一下,如给出目录:C:\Program Files\Common Files\DESIGNER,需要检测的目录是:C:\Program Files\Common Files\System,即从给出的目录中获取前面的信息,后面的补上的目录(System)是指定的。从E:\res\tmp目录中检测xml文件,返回xml文件的目录
代码如下: 1 import os 2 import re
3 pathlist = []
4 patternxml = r'.+\.xml$'
5
6 def collectxmlfile(path)
7 if re.search(r'\\Program Files\\Common Files',path)
8 path = path.split('Common Files')[0]
9 l = [path ,'\Common Files\System']
10 path = ''.join(l)
11 pathlistfinal = pathlist
12 for file in os.listdir(path):
13 file = os.path.join(path,file)
14 if (os.path.isdir(file) == False):
15 if (re.match(patternxml,file)):
16 pathlistfinal.append(file)
17 else:pass
18 else:
19 collectxmlfile(file)
20 return pathlistfinal
21 collectxmlfile(r'C:\Program Files\Common Files\DESIGNER')
这里面,为什么第二次递归到collectxmlfile()的时候不会search匹配上呢?
因为在第9行,Common前面多加了一个'\',这样第二次迭代的时候path中Common前面会有两个'\\',search中的r'\\Program Files\\Common Files'只能匹配Common前面的一个反斜杠;但path目录中多反斜杠,对于windows目录的识别是不影响的,os.listdir(path)仍然会正确的识别目录,不会因为多了一个反斜杠找不到目录,如'C:\Program Files\\Common Files\DESIGNER'。
不过这种巧妙的方式易读性差一些,我查了好几天才弄明白,比较正常的做法是把目录识别放到迭代函数外面,处理后再传参进迭代的函数。 |
|
|