I'm trying to rename multiple files in a directory using this Python script:
import os
path = '/Users/myName/Desktop/directory'
files = os.listdir(path)
i = 1
for file in files:
os.rename(file, str(i)+'.jpg')
i = i+1
When I run this script, I get the following error:
Traceback (most recent call last):
File "rename.py", line 7, in <module>
os.rename(file, str(i)+'.jpg')
OSError: [Errno 2] No such file or directory
Why is that? How can I solve this issue?
Thanks.


fileslist will contain all the files in givenpath, but when you doos.rename(), it looks for a file in current working directory.os.listdir()returns just the filenames and not the full path of the file. Useos.path.join(path, file)to get the full path and rename that.