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)
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)
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)
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)