Use python batch modify file name when video merge

I do not know if you have not encountered such a situation, such as when merging video file name is not arranged in regular order, like this

can be seen, the file name is the sort of chaos. Like this video out of the merger must also be messy. So we have to find ways to modify the file name and let the software read out the correct order. Without further ado, on the code.

"""
注意:一、文件名除去扩展名必须以 '_' + 数字 结尾。
    二、convert.py 放在文件目录。
    三、目录中不能有多余文件
主要算法:
根据最大数字的位数添加0
例如,如果最大数字为123,那么位数为3位,
    1就要变成001、2变成002、23变成023,依次...
"""
import os

li = []
new_li = [] # 新文件名
null_li = []    # 不标准的文件名
filenames = os.listdir('./')

# 得到数字的最大位数
for filename in filenames:
    tmp = os.path.splitext(filename)[0] # 得到文件名
    if('_' in tmp): # 找到数字前的标志
        num = tmp.split('_')[-1]
        li.append(num)
    else:
        null_li.append(filename)
max_len = len(max(li, key=len))
# ~ print(max_len)

# 新文件名
for filename in filenames:
    name = os.path.splitext(filename)[:-1]  # 得到文件名
    name = '_'.join(name)
    ext = os.path.splitext(filename)[-1]    # 得到扩展名
    if('_' in name):    # 找到数字前的标志
        name1 =  name.split('_')[:-1]
        name1 = '_'.join(name1) #文件名
        num = name.split('_')[-1]
        quantity = max_len - len(num)
        name2 = '0' * quantity + num    #数字名
        filename = name1 + '_' + name2 + ext
        new_li.append(filename)
# ~ new_li.sort()
# ~ print(filenames)
# ~ print('\n')
# ~ print(new_li)

# 检查是否有不规范的文件名
if(len(filenames)-1 != len(new_li)):
    null_li.remove('convert.py')
    null_li = '、'.join(null_li)
    print("error: \""+ null_li + "\" 不以 '_' + 数字 结尾。")
    exit()

# 修改文件名
i = 0
for oldname in filenames:
    if (oldname != 'convert.py'):
        os.rename(oldname,new_li[i])
        print(oldname,'======>',new_li[i])
        i+=1

Which notes, in the above code also illustrates. After a successful run, again to see

visible, the video had arrayed in order.

Guess you like

Origin www.cnblogs.com/sfriend/p/11355162.html