Python concatenate text files

后端 未结 12 2152
無奈伤痛
無奈伤痛 2020-11-22 02:51

I have a list of 20 file names, like [\'file1.txt\', \'file2.txt\', ...]. I want to write a Python script to concatenate these files into a new file. I could op

12条回答
  •  一向
    一向 (楼主)
    2020-11-22 03:07

    An alternative to @inspectorG4dget answer (best answer to date 29-03-2016). I tested with 3 files of 436MB.

    @inspectorG4dget solution: 162 seconds

    The following solution : 125 seconds

    from subprocess import Popen
    filenames = ['file1.txt', 'file2.txt', 'file3.txt']
    fbatch = open('batch.bat','w')
    str ="type "
    for f in filenames:
        str+= f + " "
    fbatch.write(str + " > file4results.txt")
    fbatch.close()
    p = Popen("batch.bat", cwd=r"Drive:\Path\to\folder")
    stdout, stderr = p.communicate()
    

    The idea is to create a batch file and execute it, taking advantage of "old good technology". Its semi-python but works faster. Works for windows.

提交回复
热议问题