Home > Article > Backend Development > Python magic operation! Out-of-order file renaming numbers!
As shown in the figure below, there is a bunch of video files in the local folder. In this case, they are not out of order.
#But after uploading it to the network disk, it will often become out of order. That is, they will be sorted according to 1, 10, 11, 2, 20, which is not convenient for us to watch them in order.
So we hope to be able to rename them locally. For example, we can sort them according to 001, 002, 003···, 020, so as to avoid the above embarrassment. situation.
In Python, the os module can be used to automatically handle various files and directories, such as copying, moving, renaming, and deleting operations.
Enter the following command in the interactive environment:
import os path =os.getcwd() filenames = os.listdir(path) filenames
Output:
os module The getcwd() function in , you can use it to get the current working directory. The listdir() function in the os module can return all files and subdirectories in the working directory. Through these two functions, we obtain all files in the current working directory.
Enter the following command in the interactive environment:
file_mp4s = [i for i in filenames if i.split(".")[-1] == "mp4"] file_mp4s
Output:
This Step is used to filter all mp4 files in the file list. Using loop conditions is too cumbersome, but list generation can get the video file with one line of statements.
Enter the following command in the interactive environment:
for i in file_mp4s: new_name = i.split("-")[0].zfill(3) + "-" + i.split("-")[1] os.rename(i,new_name)
Output:
os module The rename() function in , you can use it to rename files.
A string function zfill() is also used here, which will return a string of specified length. The original string is right-aligned and filled with 0s in front. So "1".zfill(3) will return '001'.
In this way, we have achieved the renaming and numbering of out-of-order files. I hope today’s sharing can be helpful to you~
The above is the detailed content of Python magic operation! Out-of-order file renaming numbers!. For more information, please follow other related articles on the PHP Chinese website!