如何在 Python 中连接文件? [英] How do I concatenate files in Python?

查看:33
本文介绍了如何在 Python 中连接文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个(40 到 50 个)MP3 文件,我想将它们连接成一个文件.在 Python 中执行此操作的最佳方法是什么?

I have multiple (between 40 and 50) MP3 files that I'd like to concatenate into one file. What's the best way to do this in Python?

使用 fileinput 模块循环遍历每一行每个文件并将其写入输出文件?外包给 windows copy 命令?

Use fileinput module to loop through each line of each file and write it to an output file? Outsource to windows copy command?

推荐答案

将这些文件中的字节放在一起很容易...但是我不确定这是否会导致连续播放 - 我认为如果文件是使用相同的比特率,但我不确定.

Putting the bytes in those files together is easy... however I am not sure if that will cause a continuous play - I think it might if the files are using the same bitrate, but I'm not sure.

from glob import iglob
import shutil
import os

PATH = r'C:music'

destination = open('everything.mp3', 'wb')
for filename in iglob(os.path.join(PATH, '*.mp3')):
    shutil.copyfileobj(open(filename, 'rb'), destination)
destination.close()

这将创建一个everything.mp3"文件,其中 C:music 中所有 mp3 文件的所有字节都连接在一起.

That will create a single "everything.mp3" file with all bytes of all mp3 files in C:music concatenated together.

如果你想在命令行中传递文件名,你可以使用 sys.argv[1:] 而不是 iglob(...),等

If you want to pass the names of the files in command line, you can use sys.argv[1:] instead of iglob(...), etc.

这篇关于如何在 Python 中连接文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆