在python中加入大量文件

时间:2013-02-23 22:58:15

标签: python newline

from itertools import chain


 infiles = [open('{}_example.txt'.format(i+1), 'r') for i in xrange(100)]
   with open('example.txt', 'w') as fout:
      for lines in chain(*infiles):
           fout.write(lines)

我用过这个,但问题是下一个文件的第一行与前一个文件的最后一行连接。

2 个答案:

答案 0 :(得分:3)

我不会一次打开所有文件,而是一次打开一个文件。你也不需要遍历这些行(使Python标准化并删除换行符);只需读取整个文件(您甚至可以将它们读/写为二进制文件,以防止Python以任何方式处理它们。)

fileNames = ['{}_example.txt'.format(i+1) for i in xrange(100)]
with open('example.txt', 'w') as fout:
    for fileName in fileNames:
        with open(fileName, 'r') as fin:
            fout.write(fin.read())
            fout.write('\n') # if you want that

答案 1 :(得分:0)

尝试添加换行符

  for lines in chain(*infiles):
       fout.write(lines)
       if not lines.endswith('\n'):
           fout.write('\n')

根据mtth的建议,您可以逐个文件地执行此操作:

from itertools import chain


infiles = [open('{}_example.txt'.format(i+1), 'r') for i in xrange(100)]
with open('example.txt', 'w') as fout:
    for infile in infiles:
        fout.write(infile.read())
        fout.write('\n')