Recently, I downloaded a cartoon on the Internet, which is in the form of pictures. After downloading it, I found that the file names of each cartoon picture were irregular, long and complicated. It would be too much work to change the file names one by one, which would waste too much time. So I decided to write a script in Python to implement batch renaming.

The file is stored in D:/temp. The file name is similar to the one shown above

To complete the script, I consulted Python’s file name library and found that I needed the OS library from the Python standard library.

Rename functions

Python has a function for renaming files:

os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
Copy the code

This function simply changes the file name from SRC to DST, and the last two parameters are ignored.

Get file name function

We also need to get the original file name, SRC.

There is also a function in the OS library to get the file name:

os.listdir(path='. ')
Copy the code

This function lists all file names in a directory

So we use a for loop to get each filename

for file in os.listdir(r'D:/temp') :print(file)
Copy the code

Output:

%80%90%E4%B8%89%E7%A7%8B%E4.jpg

%AE%E5%8B%92%E6%9E%81%E7%A6.jpg

%E6%B3%B0%E6%99%AE%E5%8B%92.jpg

%E8%A3%85%E5%85%E6%B3%B0%E6.jpg

Path merge function

Since image files and Python scripts are not in the same folder, SRC and DST are not simple file names, but a path + file name. For example, the file %80%90%E4%B8%89%E7%A7%8B% e4.jpg is actually E:/temp/%80%90%E4%B8%89%E7%A7%8B% e4.jpg, so we need to combine the two parts.

The Python OS library has a function:

os.path.join(path, *paths)
Copy the code

This function reasonably concatenates one or more path parts and returns a concatenation of all the values of PATH and * Paths.

The above example could be written like this:

os.path.join(r'D:/temp'.'%80%90%E4%B8%89%E7%A7%8B%E4.jpg')
Copy the code

Batch rename scripts

GitHub-Yajanan/FilesPathRename:

# FilesBatchRename.py
# Import OS library
import os

# The path where the image is stored
path = r"D:/temp"

Change the file name
num = 1
for file in os.listdir(path):
    os.rename(os.path.join(path,file),os.path.join(path,str(num))+".jpg")
    num = num + 1
Copy the code

Run it and you can see the following result:

It meets our needs.

(End of text)

This article is published by OpenWrite, a blogging tool platform