I need to rename all files to 'DSC0 + num'
, so the final name of a file should be (for example) 'DSC02015'
Attempted code:
import os
path = "C:\\images"
num = 2000
i=0
files = os.listdir(path)
for x in files:
old = files[i]
new = 'DSC0%d' %(num)
os.rename (files[i],new)
num +=1
i +=1
I'm getting this error:
Traceback <most recent call last):
File "rename.py", line 10, in <module>
os.rename (files[i],new)
WindowsError: [Error 2] The system cannot find the file specified
You have to change to the right directory first. So put this in front of the for
-loop:
os.chdir(path)
If your python script is in another directory, that will be the working directory and since you only have filenames and not absolute file paths, the files can't be resolved in that working directory. Changing to it therefore solves your problem.
As a side note, your loop could be a bit simpler. This should do the same:
for x in files:
new = 'DSC0%d' %(num)
os.rename (x, new)
num +=1