Hello is white
When I try to sort such a file, I can sort it well in the file, but when I try to process it with Python etc.
The order may be different from what you expected. .. ..
I got stuck in this, so I will write it down as a memo for myself.
Put an extra 0000 before the subscript. This will solve the problem.
However, it's a hassle to manually rewrite all the names, so let's leave it all to Python.
As a premise, consider only adding the subscripts of the original file.
ex)img32.png ⇒ img00032.png
is. It's easy, so let's finish it one by one.
Use something called os to get the file name.
import os
file_dl = './File/'
res = os.listdir(file_dl)
With this alone, I was able to get all the names of what was in the file that was file.
Next, let's get the subscript from the obtained file name.
import re
file_index = re.search(r'\d{1,}', 'img012.png').group()
Here, we use a regular expression to get only the numbers from the string.
In this case, only 012 is extracted from img012.png and stored in file_index.
Finally, rename it and save it, using shutil. All I'm doing is renaming and moving it back to its original location.
import shutil
shutil.move(old_path,new_path)
By doing this, I was able to move what was in old_path to new_path.
If you connect the above
import os
import shutil
file_dl = './File/'
name = 'img_name'
#Get the folder name in the file
res = os.listdir(file_dl)
#Extract the files one by one using the for statement.
for target_name in res:
#Combine file path and file name
target_dl = file_dl + target_name
#Extract only subscripts using regular expressions
target_index = int(re.search(r'\d{1,}', target_name).group())
#Create a new file name
target_new_name = name+str("{0:05d}".format(target_index))+'.png'
#Rename the file and save it again
shutil.move(target_dl,file_dl+target_new_name)
Recommended Posts