Python3代码优化:批量重命名文件,处理以'h_'开头的文件

本文提供Python3代码,用于批量重命名输出目录中的mp4文件。代码根据文件名是否以'h_'开头进行不同的处理逻辑,并使用ffmpeg进行视频处理。

修改后的代码如下:

import os
import glob
from natsort import natsorted

dir_path = r'E:\home\up'
output_dir = r'E:\home\up\1'

# 当前文件夹下的所有mp4路径
L = []
for root, dirs, files in os.walk(dir_path):
    files = natsorted(files)
    for file in files:
        if os.path.splitext(file)[1] == '.mp4':
            file_path = os.path.join(root, file)
            L.append(file_path)

# 生成ffmpeg命令
commands = []
for l in L:
    if os.path.basename(l).startswith('h_'):
        new_file_name = 'h_' + os.path.basename(l)[2:]
    else:
        new_file_name = os.path.basename(l)
    ts_file = os.path.join(os.path.dirname(l), os.path.splitext(new_file_name)[0] + '.ts')
    commands.append(f'ffmpeg -i '{l}' -vcodec copy -acodec copy -bsf:v h264_mp4toannexb '{ts_file}'')

concat_command = (
    f'ffmpeg -i 'concat:{{'|'.join([os.path.join(os.path.dirname(l), os.path.splitext(os.path.basename(l))[0] + '.ts') for l in L])}}' ' \
    '-acodec copy -vcodec copy -bsf:a aac_adtstoasc ' \
    f''{os.path.join(output_dir, os.path.splitext(os.path.basename(L[0]).replace('00', '-', 1))[0][:-1].upper() + '.mp4')}''
)

# 执行ffmpeg命令
for command in commands:
    os.system(command)

os.system(concat_command)

# 删除ts文件
for ts_file in glob.glob(os.path.join(dir_path, '*.ts')):
    os.remove(ts_file)

# 截取第一个字母之后的字符串,删除之前的数字
for mp4_file in glob.glob(os.path.join(output_dir, '*.mp4')):
    file_name = os.path.basename(mp4_file)
    if file_name.startswith('h_'):
        new_file_name = 'h_' + file_name[2:].lstrip('0123456789')
    else:
        new_file_name = file_name.lstrip('0123456789')
    os.rename(mp4_file, os.path.join(output_dir, new_file_name))

代码逻辑:

  1. 遍历指定目录下的所有mp4文件,并存储其路径到列表L中。
  2. 使用ffmpeg将每个mp4文件转换为ts格式文件。
  3. 将所有ts文件合并成一个新的mp4文件。
  4. 删除所有的ts文件。
  5. 重命名output_dir目录下的所有mp4文件,将文件名中的数字部分删除。

针对以'h_'开头的文件,代码进行了以下修改:

  1. 在生成ffmpeg命令时,根据文件名是否以'h_'开头,分别生成不同的新文件名。
  2. 在重命名mp4文件时,也根据文件名是否以'h_'开头,分别进行处理。

代码特点:

  1. 使用了natsort库进行文件名排序,保证文件按自然顺序重命名。
  2. 代码结构清晰,逻辑易懂。
  3. 使用了f-string格式化字符串,提高代码可读性。

注意事项:

  1. 请确保系统中已安装ffmpeg软件。
  2. 请将代码中的dir_path和output_dir替换为实际路径。

希望本文对您有所帮助。如果您有任何问题,请随时留言。

Python3代码优化:批量重命名文件,处理以'h_'开头的文件

原文地址: https://www.cveoy.top/t/topic/nCiV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录