首页 > 解决方案 > 用部分路径名给出变量的完整路径?

问题描述

这是一个更好的版本,包括我到目前为止所做的:

这本词典:sfiles

{'C:\\Users\\user\\Desktop\\05052\\ASTTOM\\ASTTOM': [], 
'C:\\Users\\user\\Desktop\\05052\\ASTIK\\ASTIK': [], 
'C:\\Users\\user\\Desktop\\05052\\ROADS\\ROADS': []}

我想检查是否sh1在那里:

sh1
u'ASTTOM'

sh2
u'ASTIK'

sfiles我想将匹配的完整路径分配给 sh1 。

我做了什么 :

   for i in list(sfiles):
       if shape1 in os.path.basename(i):
            print((i))
            shape1 = i

这种方法是否正确,我怎样才能有效地为 sh2 做同样的事情?

标签: pythonloopsdictionary

解决方案


据我了解,您想找到最后一部分有 sh1(称为 shape1)的路径。所以,你可以这样做:

sfiles = {'C:\\Users\\user\\Desktop\\05052\\ASTTOM\\ASTTOM': [],
          'C:\\Users\\user\\Desktop\\05052\\ASTIK\\ASTIK': [],
          'C:\\Users\\user\\Desktop\\05052\\ROADS\\ROADS': []
          }

for pth in sfiles.keys():
    if shape1 in pth.split("\\")[-1]:
       print(pth)

推荐阅读