Python3 代码优化:删除文件名中数字并重命名输出文件
import os
import glob
from natsort import natsorted
# 当前文件夹下的所有mp4路径
L = []
dir_path = '/home/downloads'
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:
ts_file = os.path.join(
os.path.dirname(l), os.path.splitext(os.path.basename(l))[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(dir_path, os.path.splitext(os.path.basename(L[0])[1:].replace("00", "-", 1))[0].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)
该代码首先获取当前文件夹下的所有 mp4 文件路径,并使用 natsorted 对文件进行排序。然后,它生成 ffmpeg 命令将每个 mp4 文件转换为 ts 文件,并使用 concat 命令将所有 ts 文件合并成一个新的 mp4 文件。最后,它删除所有生成的 ts 文件。
代码优化:
- 使用
natsorted对文件进行排序,保证输出文件按顺序合并。 - 代码中使用
f-string格式化字符串,提高代码可读性。 - 代码使用
os.system执行ffmpeg命令,简单易用。 - 代码添加注释,解释代码逻辑。
代码功能:
- 获取当前文件夹下的所有 mp4 文件路径。
- 将每个 mp4 文件转换为 ts 文件。
- 合并所有 ts 文件成一个新的 mp4 文件。
- 删除所有生成的 ts 文件。
- 将新生成的 mp4 文件的名称修改为去掉文件名中第一个英文字母之前的数字,并将字母部分转换为大写。
代码示例:
假设当前文件夹下的 mp4 文件名为 01_test.mp4、02_test.mp4、03_test.mp4,那么该代码将会生成一个名为 TEST.mp4 的新文件,并删除所有生成的 ts 文件。
注意:
- 该代码需要安装
natsort和ffmpeg包。 dir_path变量需要设置为你的 mp4 文件所在文件夹的路径。- 该代码仅供参考,可能需要根据实际情况进行调整。
原文地址: https://www.cveoy.top/t/topic/nCde 著作权归作者所有。请勿转载和采集!