Python文件计数器脚本无法正常工作

时间:2018-08-30 10:00:50

标签: python file count

为什么'cycleNumber'的计数不超过10?

enter image description here

import os

cycleNumber = 1
for files in os.listdir('Cycles'):
    if files.startswith('Cycle' + str(cycleNumber)):
        cycleNumber += 1

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