Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
88 views
in Technique[技术] by (71.8m points)

How do I concatenate files in 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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...