Home > Blockchain >  Python os.walk looping folders in a pattern to rename
Python os.walk looping folders in a pattern to rename

Time:04-16

Hi I'm trying to learn the os.walk module

Thank you in advance

Aim: rename all folders in 'student folder' To read 1, 2 ,3 ,4

Problem: My code only renames the first folder to 1 successfully others remain the same.

for root, sub, files in os.walk(my_dir):
    for x in sub:
        count = 0
        new_name = count   1
        os.rename(f'{root}/{x}', f'{root}/{new_name}')

CodePudding user response:

Whenever you're implementing a counter like this, enumerate is usually the more pythonic option:

for root, sub, files in os.walk(my_dir):
    for count, x in enumerate(sub):
        os.rename(f'{root}/{x}', f'{root}/{count}')

CodePudding user response:

It looks like you never increase the count. You might as well drop the new_name variable completely and go for something like this:

for root, sub, files in os.walk(my_dir):
    count = 0 
    for x in sub:
        count  = 1
        os.rename(f'{root}/{x}', f'{root}/{count}')
  • Related