在python中组合文本文件

时间:2016-12-11 18:28:46

标签: python

我正在尝试将多个文本文件合并到一个文件中的目录中。我想在组合文件中编写HEADER和END语句。我正在使用的当前python脚本将所有文件合并为一个,但我无法弄清楚如何为combine文件中的每个文件编写HEADER和END语句。

filenames = ['pm.pdb.B10010001.txt', 'pm.pdb.B10020001.txt', ...]
with open('/pdb3c91.0/output.txt', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            for line in infile:
                outfile.write(line)

1 个答案:

答案 0 :(得分:2)

只需写下两行。

filenames = ['pm.pdb.B10010001.txt', 'pm.pdb.B10020001.txt', ...]
with open('/pdb3c91.0/output.txt', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            outfile.write("HEADER\n")
            for line in infile:
                outfile.write(line)
            outfile.write("END\n")