Reputation: 159
In the code below, at if path_parts[-2:-1]=='training'
I want my function to step into counting files at that location. My print(path_parts[-2:-1])
demonstrates that the code is finding the 'training' folder I'm looking for but the evaluation doesn't prove 'true'.
What am I doing wrong?
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']
Upvotes: 1
Views: 53
Reputation: 152820
Your path_parts[-2:-1]
returns a list (because you slice the list) and you then compare it with a string 'training'
. That's always False
because these lists and strings are incomparable.
But you can simply access the second-last item with path_parts[-2]
:
if path_parts[-2] == 'training':
Upvotes: 3
Reputation: 59232
As you can see from your output, path_parts[-2:-1]
is ['training']
. That's a list. But you're comparing it to 'training'
, which is a string.
You mean:
# Is this sublist equal to a list containing the string 'training'?
if path_parts[-2:-1] == ['training']:
or more simply:
# Is the element at position -2 equal to the string 'training'?
if path_parts[-2] == 'training':
Upvotes: 3