I was converting a video to frames and storing those frames in a directory with format "Anime Season 1 episode 1 - Frame 1 of 89000" and so on. But i found out that I put the total number of frames wrong. So i just want to change the 89000 to 90000 in every filename i.e "Anime Season 1 episode 1 - Frame 1 of 90000". Obviosuly it is very difficult to rename each and every one of those files manually. I tried the following code in python. It changes the name of all files but it disrupts the order of the files like it renames the frame number 100 to 3 and 4 to something else. How to avoid this?
import os
path = os.chdir("C:\\Users\\xxx\\Desktop\\Rename\\Season")
i = 1
for file in os.listdir(path):
new_file_name = "Anime Season 1 episode 1 - Frame {} of 90000.jpg".format(i)
os.rename(file, new_file_name)
i = i 1
CodePudding user response:
How about defining the new file name from the original file name without using i
?
for file in os.listdir(path):
new_file_name = file.replace("89000.jpg", "90000.jpg")
os.rename(file, new_file_name)
E.g.,
file = "Anime Season 1 episode 1 - Frame 123 of 90000.jpg"
file.replace("89000.jpg", "90000.jpg")
# 'Anime Season 1 episode 1 - Frame 123 of 90000.jpg'
This way, you won't lose the original numbering.
CodePudding user response:
You should add a check on the filename itself or make sure they are ordered as you expect them to be (alphabetically, by last modification, by size... etc). Python does not necessarily parse your files the same way windows shows them...
In your case, I would simply use a replace call...
import os
path = os.chdir("C:\\Users\\xxx\\Desktop\\Rename\\Season")
i = 1
for file in os.listdir(path):
os.rename(file, file.replace("89000.jpg", "90000.jpg"))
i = i 1