如何在Python中连接文件?

Owe*_*wen 36 python mp3 file

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

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

nos*_*klo 47

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

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()
Run Code Online (Sandbox Code Playgroud)

这将在C上创建的所有MP3文件的所有字节一个单一的"everything.mp3"文件:\音乐连接在一起.

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


Nat*_*man 34

只是为了总结(并从nosklo的答案中窃取),为了连接你做的两个文件:

destination = open(outfile,'wb')
shutil.copyfileobj(open(file1,'rb'), destination)
shutil.copyfileobj(open(file2,'rb'), destination)
destination.close()
Run Code Online (Sandbox Code Playgroud)

这与:

cat file1 file2 > destination
Run Code Online (Sandbox Code Playgroud)


tue*_*ist 5

嗯.我不会用"线".使用快速而肮脏

outfile.write( file1.read() )
outfile.write( file2.read() )
Run Code Online (Sandbox Code Playgroud)

;)

  • 是的我知道.但.我写的"快而脏".这意味着:没有保证...... (2认同)