python printing out a file with a suffix range of 12

Question:

So I have been trying to get a filename to end with a repeat of 01-12, then start over. Any help would be appreciated.

def rname(f=None):
    os.chdir(dir_path)
    print("Renaming Files.")
    print(os.getcwd())
    for count, f in enumerate(os.listdir()):
        f_name = os.path.splitext(f)[0]
        ext_name = os.path.splitext(f)[1]
        br = (f_name[0:7] + str(("{:02d}".format(count +1) in range [:12])))
        new_name = f'{br}{ext_name}'
        print(new_name)
        os.rename(f, new_name)
Asked By: w j

||

Answers:

you are probably looking for itertools.cycle to keep cycling between 1 and 12 indefinitely.

import os
import itertools

def rname(f=None):
    # os.chdir(dir_path)
    print("Renaming Files.")
    print(os.getcwd())
    for index, f in zip(itertools.cycle(range(1,13)), os.listdir()):
        f_name = os.path.splitext(f)[0]
        ext_name = os.path.splitext(f)[1]
        br = f_name[0:7] + "{:02d}".format(index)
        new_name = f'{br}{ext_name}'
        print(new_name)
        # os.rename(f, new_name)

rname()

another useful thing to use is the modulo operator % to keep the number below 12.

    for index, f in enumerate(os.listdir()):
        f_name = os.path.splitext(f)[0]
        ext_name = os.path.splitext(f)[1]
        br = f_name[0:7] + "{:02d}".format((index % 12) + 1)
Answered By: Ahmed AEK
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.