在下面的代码中,在if path_parts[-2:-1]=='training'
处,我希望函数进入该位置的文件计数。我的print(path_parts[-2:-1])
演示了代码正在找到我要查找的“ training”文件夹,但评估结果却未证明是“ true”。
我究竟做错了什么?
for dirs_name, sub_dirs, files in os.walk(file_path):
count=0
name=''
if os.path.basename(dirs_name)== '2016':
path_parts = [x.lower() for x in dirs_name.split('\\')]
print(path_parts[-2:-1])
if path_parts[-2:-1] == 'training':
'statement'
Output of the print statement
['training']
['training']
['training']
['training']
最佳答案
从输出中可以看到,path_parts[-2:-1]
是['training']
。那是一张清单。但是您正在将其与'training'
(它是一个字符串)进行比较。
你的意思是:
# Is this sublist equal to a list containing the string 'training'?
if path_parts[-2:-1] == ['training']:
或更简单地说:
# Is the element at position -2 equal to the string 'training'?
if path_parts[-2] == 'training':