tags:

views:

2219

answers:

3

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?

+9  A: 

to put 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.

nosklo
you don't need fullname step there, glob is already producing absolute filenames.
SilentGhost
and you can use iglob, instead of glob
SilentGhost
@SilentGhost: Thanks, fixed
nosklo
I have no clue if it will cause continuous play or not - guess I'll find out - and maybe ask another question about it...haha.
Owen
This solution does impact continuous play - in that it doesn't happen. There's some skipping in the spots where MP3s were joined. This is fine for my application though.
Owen
What does the `r` in `r'C:\music'` do?
Nathan Fellman
@Nathan Fellman: read up on raw strings.
nosklo
+1  A: 

Hmm. I won't use "lines". Quick and dirty use

outfile.write( file1.read() )
outfile.write( file2.read() )

;)

tuergeist
Though this won't work for very large flies.
Nathan Fellman
Yes, I know. But. I wrote "quick and dirty". That implies: without guaranties...
tuergeist
+3  A: 

Just to summarize (and steal from nosklo's answer), in order to concatenate two files you do:

destination = open(outfile,'wb')
shutil.copyfileobj(open(file1,'rb'), destination)
shutil.copyfileobj(open(file2,'rb'), destination)
destination.close()

This is the same as:

cat file1 file2 > destination
Nathan Fellman