How do I concatenate files in Python? How do I concatenate files in Python? python python

How do I concatenate files in Python?


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 iglobimport shutilimport osPATH = 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.


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


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

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

;)