Python concatenate text files

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

    Check out the .read() method of the File object:

    http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

    You could do something like:

    concat = ""
    for file in files:
        concat += open(file).read()
    

    or a more 'elegant' python-way:

    concat = ''.join([open(f).read() for f in files])
    

    which, according to this article: http://www.skymind.com/~ocrow/python_string/ would also be the fastest.

提交回复
热议问题