崭新的蟒蛇和难倒的所有准备好,会很感激一手。
testn1 = {'names':('tn1_name1','tn1_name2','tn1_name3'),'exts':('.log','.txt')}
testn2 = {'names':('tn2_name1'),'exts':('.nfo')}
testnames = {1:testn1,2:testn1}
directory = 'C:\\temp\\root\\'
for subdir in os.listdir(directory):
# check if name of sub directory matches the name in any of the dicts in testnames[testn*]['names']
if os.path.isdir(os.path.join(directory, subdir)) and [subdir in subdir.lower() in testnames[testn1]['names']]: # this works but need to iterate through all dicts
print(subdir)
# if the a dir name matches do a recursive search for all filenames that exist in the same dict with the corresponding extensions
for dirname, dirnames, filenames in os.walk(os.path.join(directory, subdir)):
for file in filenames:
if file.endswith(testnames[testn1]['exts']): # this works but need to match with corresponding folder
print(file)
我以为我能够做这样的事情,但我确信我对python的理解不是它需要的。
if os.path.isdir(os.path.join(directory, subdir)) and [subdir in subdir.lower() in [for testnames[key]['names'] in key, value in testnames.items()]]:
我希望以这种方式保持结构,但对任何事情都是开放的。
编辑:我最终选择......if os.path.isdir(os.path.join(directory, subdir)) and [i for i in testnames.values() if subdir.lower() in i['names']]:
感谢@ pzp1997关于.values()
的抬头答案 0 :(得分:1)
不完全确定你想要什么,但我认为就是这样:
if os.path.isdir(os.path.join(directory, subdir)) and subdir.lower() in [i['names'] for i in testnames.values()]
答案 1 :(得分:1)
这样做了!
if os.path.isdir(os.path.join(directory, subdir)) and [i for i in testnames.values() if subdir.lower() in i['names']]:
答案 2 :(得分:0)
相反呢?
testn1 = {'names':('tn1_name1','tn1_name2','tn1_name3'),'exts':('.log','.txt')}
testn2 = {'names':('tn2_name1'),'exts':('.nfo')}
testnames = {1:testn1,2:testn1}
directory = 'C:\\temp\\root\\'
for dirname, _, filenames in os.walk(directory):
the_dir = os.path.split(dirname)[-1]
for testn in testnames.itervalues():
if the_dir in testn['names']:
for file in filenames:
_, ext = os.path.splitext(file)
if ext in testn['exts']:
print the_dir, file