Reputation: 85
I have a number of image files stored as 0.png, 1.png, ..., x.png in a folder. I have to rename then in the opposite order, i.e. 0->x, 1->(x-1), .., (x-1)->1, x->0. I have written the following code in python.
for filename in os.listdir("."):
tempname = "t" + filename
os.rename(filename, tempname)
for x in range(minx, maxx+1):
tempname = "t" + str(x) + ".png"
newname = str(maxx-x) + ".png"
os.rename(tempname, newname)
I encounter the following error:
OSError: [Errno 2] No such file or directory
What am I doing wrong? Is there a smarter way of doing this?
Upvotes: 0
Views: 1821
Reputation: 46759
Try the following, it uses the glob
module to get the file list. This should include the full path otherwise os.rename
could fail:
import glob
import os
source_files = glob.glob(r'myfolder\mytestdir\*')
temp_files = ['{}.temp'.format(file) for file in source_files]
target_files = source_files[::-1]
for source, temp in zip(source_files, temp_files):
os.rename(source, temp)
for temp, target in zip(temp_files, target_files):
os.rename(temp, target)
Note, if you want to target just .png
files, you could change the glob line to be *.png
Upvotes: 2