首页 > 解决方案 > 仅将 mp4 文件与 Pathlib 合并

问题描述

我只想知道这是否可能不使用shutil合并文件?但仅使用 pathlib。

我用于合并文件的旧代码:

 def combine(source: str, output: str),
 
    with open(output, 'wb') as output_file:
        for file in iglob(os.path.join(source, "*.mp4")):
            print(f'Merging', file, end='\r')
            with open(file, 'rb') as input_file:
                shutil.copyfileobj(input_file, output_file)

这是我尝试使用 pathlib

def combine(source: str, output: str),

    for file in Path(source).glob('*.mp4'):
        print(f'Merging', file)
        Path(output).write_bytes(file.read_bytes())

问题是,它没有附加字节并组合到输出文件。

标签: python

解决方案


您应该只打开一次输出文件,然后写入您读取的每个文件的字节。

def combine(source: str, output: str),
    print(f'Creating {output}')
    with open(Path(output), 'wb') as outfile:    

        for file in Path(source).glob('*.mp4'):
            print(f'Appending {file}')
            outfile.write(file.read_bytes())  

推荐阅读