Renaming multiple files in a directory using Python

I am trying to rename multiple files to 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? How can I solve this problem?

Thank.

+16
python directory rename
May 26 '16 at 17:33
source share
5 answers

You do not give all the way when renaming, do it like this:

 import os path = '/Users/myName/Desktop/directory' files = os.listdir(path) for index, file in enumerate(files): os.rename(os.path.join(path, file), os.path.join(path, str(index)+'.jpg')) 

Edit : Thanks to tavo, the first solution will move the file to the current directory, fixed it.

+53
May 26 '16 at 17:40
source share

First you must make this path as the current working directory. simple enough. the rest of the code has no errors.

to make it the current working directory:

 os.chdir(path) 
+4
Jul 23 '17 at 18:32
source share

According to @daniel's comment, os.listdir () only returns file names, not the full path to the file. Use os.path.join (path, file) to get the full path and rename it.

 import os path = 'C:\\Users\\Admin\\Desktop\\Jayesh' files = os.listdir(path) for file in files: os.rename(os.path.join(path, file), os.path.join(path, 'xyz_' + file + '.csv')) 
+2
Mar 26 '18 at 15:21
source share

If your files are renamed randomly, then first you need to sort the files in the directory. This code sorts and renames files first.

 import os import re path = 'target_folder_directory' files = os.listdir(path) files.sort(key=lambda var:[int(x) if x.isdigit() else x for x in re.findall(r'[^0-9]|[0-9]+', var)]) for i, file in enumerate(files): os.rename(path + file, path + "{}".format(i)+".jpg") 
0
Feb 27 '19 at 13:20
source share

I worked on a fast and flexible script to take care of displaying the differences, requesting confirmation, and renaming. If you need a working solution, you can copy this script and put it in the folder where you want to rename the files. https://gist.github.com/aljgom/81e8e4ca9584b481523271b8725448b8

It renames files in the current directory, passing "rename functions", each function can take care of the change. It then identifies the changes that each function will make and displays the differences using colors, and asks for confirmation to make the changes. Powered by pycharm, did not test it on different consoles

-one
09 Oct '18 at 2:24
source share



All Articles