我正在用这个来整理文件:

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


如何修改脚本,以便做到这一点?

最佳答案

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

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


编辑:如果您需要在每个文件之后编写代码,则可以在处理的每个文件之后简单地写换行,write()将任何字符串作为参数并编写它:

    with open(fname) as infile:
        outfile.write(infile.read())
    outfile.write("\n\n")

关于python - 如何在串联文件之间添加空白行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33462685/

10-13 02:07