0

Why does 'cycleNumber' not count above 10?

enter image description here

import os

cycleNumber = 1
for files in os.listdir('Cycles'):
    if files.startswith('Cycle' + str(cycleNumber)):
        cycleNumber += 1
3
  • 3
    Because the list returned by os.listdir() is not sorted numerically as you think. Commented Aug 30, 2018 at 10:06
  • In these kinds of situations put some print statements in to see what data you are dealing with. In this case the print would go in between the for and the if. Commented Aug 30, 2018 at 11:51
  • 1
    Please don't make more work for other people by vandalizing your posts. By posting on the Stack Exchange (SE) network, you've granted a non-revocable right, under the CC BY-SA 3.0 license, for SE to distribute that content (i.e. regardless of your future choices). By SE policy, the non-vandalized version of the post is the one which is distributed. Thus, any vandalism will be reverted. If you want to know more about deleting a post please see: How does deleting work? ... Commented Jan 14, 2019 at 5:02

1 Answer 1

2

You are only iterating over the list returned from os.listdir() (which is not in any particular order) once. This means that if the files were given in an unexpected order such as:

Cycle2.txt
Cycle1.txt

Then it would take till the second iteration for the cycleNumber to increment from 1 to 2, but by then you have already gone passes Cycle2.txt!


Instead, you should use a while loop:

import os
cycleNumber = 0
while any(f.startswith('Cycle' + str(cycleNumber+1)) for f in os.listdir('Cycles')):
    cycleNumber += 1

A test:

$ mkdir Cycles
$ for i in {1..11}; do touch Cycles/Cycle$i.txt; done;
$ python -q
>>> import os
>>> cycleNumber = 0
>>> while any(f.startswith('Cycle' + str(cycleNumber+1)) for f in os.listdir('Cycles')):
...     cycleNumber += 1
... 
>>> cycleNumber
11
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.