SoFunction
Updated on 2024-11-15

Method to batch change filenames using python (when merging videos)

I do not know if you have encountered such a situation, such as video merging file names are not in the normal order, like this

  

As you can see, the file name sorting is messed up. This way the merged video must be messed up as well. So we have to find a way to modify the file name, so that the software read out the correct order. Without further ado, on the code.

"""
Note: i. Filenames minus extensions must end with '_' + number. ii.
II. Place in the Documents directory.
Third, there should be no redundant files in the directory
Main Algorithm:
Add 0 according to the number of digits of the largest number
For example, if the maximum number is 123, then the number of digits is 3.
1 will become 001, 2 will become 002, 23 will become 023, in that order...
"""

import os

li = []
new_li = [] # New filename
null_li = [] # Non-standardized file names
filenames = ('./')

# Get the maximum number of digits of a number
for filename in filenames:
 tmp = (filename)[0] # Get the filename
 if('_' in tmp): # Find the sign before the number
 num = ('_')[-1]
 (num)
 else:
 null_li.append(filename)
max_len = len(max(li, key=len))
# ~ print(max_len)

# New filename
for filename in filenames:
 name = (filename)[:-1] # Get the filename
 name = '_'.join(name)
 ext = (filename)[-1] # Get the extension
 if('_' in name): # Find the sign before the number
 name1 = ('_')[:-1]
 name1 = '_'.join(name1) # file name
 num = ('_')[-1]
 quantity = max_len - len(num)
 name2 = '0' * quantity + num # Number Name
 filename = name1 + '_' + name2 + ext
 new_li.append(filename)
# ~ new_li.sort()
# ~ print(filenames)
# ~ print('\n')
# ~ print(new_li)

# Check for irregular file names
if(len(filenames)-1 != len(new_li)):
 null_li.remove('')
 null_li = '、'.join(null_li)
 print("error: \""+ null_li + "\" does not end with '_' + number.")
 exit()

# Modify the file name
i = 0
for oldname in filenames:
 if (oldname != ''):
 (oldname,new_li[i])
 print(oldname,'======>',new_li[i])
 i+=1

One of the caveats is also explained in the above code. After running successfully, check again the


As you can see, the videos are already in order.

summarize

The above is a small introduction to the video merger using python batch file name change party, I hope to help you, if you have any questions please leave me a message, I will reply to you in a timely manner. Here also thank you very much for your support of my website!
If you find this article helpful, please feel free to reprint it, and please note the source, thank you!