为什么'cycleNumber'的计数不超过10?
import os
cycleNumber = 1
for files in os.listdir('Cycles'):
if files.startswith('Cycle' + str(cycleNumber)):
cycleNumber += 1
答案 0 :(得分:2)
您只需遍历os.listdir()
返回的列表(顺序不特定)。这意味着,如果文件以意外顺序提供,例如:
Cycle2.txt
Cycle1.txt
然后,cycleNumber
将从1
递增到2
直到第二次迭代,但是到那时您已经通过了Cycle2.txt
!
相反,您应该使用while循环:
import os
cycleNumber = 0
while any(f.startswith('Cycle' + str(cycleNumber+1)) for f in os.listdir('Cycles')):
cycleNumber += 1
测试:
$ 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