Python concatenate text files

后端 未结 12 2284
無奈伤痛
無奈伤痛 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:24

    If the files are not gigantic:

    with open('newfile.txt','wb') as newf:
        for filename in list_of_files:
            with open(filename,'rb') as hf:
                newf.write(hf.read())
                # newf.write('\n\n\n')   if you want to introduce
                # some blank lines between the contents of the copied files
    

    If the files are too big to be entirely read and held in RAM, the algorithm must be a little different to read each file to be copied in a loop by chunks of fixed length, using read(10000) for example.

提交回复
热议问题