2009-06-16 35 views
33

我有多個(40到50個)MP3文件,我想要連接成一個文件。在Python中執行此操作的最佳方式是什麼?如何在Python中連接文件?

使用fileinput通過每個文件的每一行模塊循環,並將其寫入到輸出文件?外包給windows copy命令?

+0

http://stackoverflow.com/a/27077437/1157720 – sajjadG 2016-01-21 12:55:15

回答

44

把字節的文件放在一起很容易......但我不知道這是否會導致連續播放 - 我想這可能,如果這些文件都使用相同的比特率,但我不知道。

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

這將創建一個在C中的所有MP3文件的所有字節一個單一的「everything.mp3」文件:\音樂連接在一起。

如果你想通過在命令行中的文件名,你可以使用sys.argv[1:]代替iglob(...)

+0

你不需要全名步驟那裏,glob已經在生成絕對文件名了。 – SilentGhost 2009-06-16 13:48:26

+0

,你可以使用iglob,而不是glob – SilentGhost 2009-06-16 13:49:00

5

嗯。我不會使用「線條」。快速和骯髒的使用

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

;)

32

只是爲了總結(從nosklo's answer偷),爲了連接兩個文件,你這樣做:

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

這是一樣的:

cat file1 file2 > destination