简体   繁体   中英

python for loop in os.walk()

i write this code to get the count of files inside my directory but i need it to count the output lines when it run ...

import os
for dir,subdir,files in os.walk(r"C:\Users\adam\Desktop\test"):
    i = 0 
    i = i + 1 
    print(str(i) + ": files "+str(len(files)))

output :

1: files 3
1: files 0
1: files 0

the line number is does not change it's stay 1 ?? how i can solve it and explain why please i need to understand

because you are initializing i =0 in every iteration

import os
i = 0 
for dir,subdir,files in os.walk(r"C:\Users\adam\Desktop\test"):
    i = i + 1 
    print(str(i) + ": files "+str(len(files)))

this is pretty obvious as

i = 0 
i = i + 1 

in a row is equivalent to

i = 1

Don't handle your indices yourself. Use enumerate instead, starting at 1, and since you're not using the dir parts, just anonymize them when unpacking.

for i,(_,_,files) in enumerate(os.walk(r"C:\Users\adam\Desktop\test"),1):
    print("{} : files ".format(i,len(files)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM