Python3 代码优化:去除输出文件名最后一个字母,不含后缀

以下代码示例展示了如何修改 Python3 代码,以便在输出文件名时去除最后一个字母,但不包括文件后缀。

import os
import glob
from natsort import natsorted

# 当前文件夹下的所有mp4路径
L = []
dir_path = '/home/115/up'
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][:-1] + '.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][:-1] + '.ts') for l in L])}' -acodec copy -vcodec copy -bsf:a aac_adtstoasc '{os.path.join(dir_path, os.path.splitext(os.path.basename(L[0]))[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)

代码说明:

  1. 代码使用 os.path.splitext(os.path.basename(l))[0][:-1] 来提取文件名,并使用 [:-1] 去除最后一个字母。
  2. 代码使用 natsorted 对文件进行自然排序,确保输出文件按顺序排列。
  3. 代码使用 glob 库来删除生成的 .ts 文件。

修改后的代码示例:

import os
import glob
from natsort import natsorted

# 当前文件夹下的所有mp4路径
L = []
dir_path = '/home/115/up'
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][:-1] + '.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][:-1] + '.ts') for l in L])}' -acodec copy -vcodec copy -bsf:a aac_adtstoasc '{os.path.join(dir_path, os.path.splitext(os.path.basename(L[0]))[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)

代码说明:

  1. 代码使用 os.path.splitext(os.path.basename(l))[0][:-1] 来提取文件名,并使用 [:-1] 去除最后一个字母。
  2. 代码使用 natsorted 对文件进行自然排序,确保输出文件按顺序排列。
  3. 代码使用 glob 库来删除生成的 .ts 文件。
Python3 代码优化:去除输出文件名最后一个字母,不含后缀

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

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