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.
You can copy this script and place it in the folder of which you want to rename files. https://gist.github.com/aljgom/81e8e4ca9584b481523271b8725448b8
It renames files in current directory by passing it functions. First determines the changes that will be made and displays the differences using colors, and asks for confirmation to perform the changes. Works on pycharm, haven't tested it in different consoles
You have to make this path as a current working directory first. simple enough. rest of the code has no errors.
to make it current working directory:
As per @daniel's comment, os.listdir() returns just the filenames and not the full path of the file. Use os.path.join(path, file) to get the full path and rename that.
You are not giving the whole path while renaming, do it like this:
Edit: Thanks to tavo, The first solution would move the file to the current directory, fixed that.