如何在连接文件之间添加一个空的新行?

时间:2015-11-01 13:33:47

标签: python

我用以下内容来传播文件:

filenames = ['ch01.md', 'ch02.md', 'ch03.md', 'ch04.md', 'ch05.md']
with open('chall.md', 'w') as outfile:
  for fname in filenames:
    with open(fname) as infile:
      outfile.write(infile.read())

问题是,我最终得到了这个:

## Title 1

Text 1
## Title 2

Text 2

我想要这个:

## Title 1

Text 1

## Title 2

Text 2

如何修改脚本以便这样做?

2 个答案:

答案 0 :(得分:2)

而不是在每一行之后写作(如Dimitris Jim建议的那样)在每个文件之后写:

with open('chall.md', 'w') as outfile:
  for fname in filenames:
    with open(fname) as infile:
      outfile.write(infile.read())
    outfile.write("\n\n")

答案 1 :(得分:0)

通过迭代infile中的每一行并在每次向\n\n写一行时添加两个换行符outfile来显式添加它们:

with open(fname) as infile:
  for line in infile:
      outfile.write(line + "\n\n")

编辑: 如果您需要在每个文件之后编写,您只需在处理完的每个文件后编写新行,{{1}将任何字符串作为参数并写入:

write()