【问题标题】:How do I concatenate files in Python?如何在 Python 中连接文件?
【发布时间】:2010-11-03 08:17:32
【问题描述】:

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

使用fileinput 模块循环遍历每个文件的每一行并将其写入输出文件?外包给windowscopy命令?

【问题讨论】:

标签: python file mp3


【解决方案1】:

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

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

这将创建一个“everything.mp3”文件,将 C:\music 中所有 mp3 文件的所有字节连接在一起。

如果要在命令行中传递文件名,可以使用sys.argv[1:]代替iglob(...)等。

【讨论】:

  • 这里不需要全名步骤,glob 已经在生成绝对文件名。
  • 你可以使用 iglob,而不是 glob
  • 我不知道它是否会导致连续播放——我想我会发现的——也许会问另一个问题......哈哈。
  • 此解决方案确实会影响连续播放 - 因为它不会发生。在加入 MP3 的地方有一些跳过。不过,这对我的应用程序来说很好。
  • 是我自己还是for循环行少了一个冒号?
【解决方案2】:

嗯。我不会使用“线条”。快速而肮脏的使用

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

;)

【讨论】:

    【解决方案3】:

    只是总结一下(并从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
    

    【讨论】:

    • 我试过这样做,但由于某种原因,我只得到了第一个文件,而不是附加的第二个文件。两个文件都是mp4
    【解决方案4】:

    改进了 Clint 和 nosklo,知道了上下文管理器,我觉得这样写更简洁:

    import shutil
    import pathlib
    
    source_files = pathlib.Path("My_Music").rglob("./*.mp3")
    with open("concatenated_music.mp3", mode="wb") as destination:
        for file in source_files:
            with open(file, mode="rb") as source:
                shutil.copyfileobj(source, destination)
    

    【讨论】:

      猜你喜欢
      • 2012-11-16
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 2018-10-31
      • 1970-01-01
      • 2023-03-03
      • 2023-03-10
      • 1970-01-01
      相关资源
      最近更新 更多