在python中,有时候回在一个路径下找一个不完整的路径,要将他匹配出来,用如下函数就可以,re模块提供match匹配。
path_dir为一个给定路径,roomid为一个不完整的匹配项。如下,可以将该路径下需要找的目录或者文件匹配出来。
例如:
/data/mywork hello
匹配:/data/mywork/hello_world
21 def find_dir(self, path_dir, roomid):
22 found_path = ""
23 dirt = path_dir
24 roomid = roomid
25 specify_str = roomid
26 folders = [dirt]
27 for folder in folders:
28 for x in os.listdir(folder):
29 # print "x = ", x
30 if os.path.isdir(os.path.join(folder, x)):
31 if re.match(specify_str, x):
32 found_path = x
33 print
34 "found=", x
35 return found_path