Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在每个文本文件的最后一行添加两个空行_Python_Python 2.7 - Fatal编程技术网

Python 在每个文本文件的最后一行添加两个空行

Python 在每个文本文件的最后一行添加两个空行,python,python-2.7,Python,Python 2.7,我有几个文本文件,需要在每个文件的最后添加两个额外的空行。下面的脚本在每个文本文件的最后一行添加一个空格。如何再添加一个空行?先谢谢你 import glob for file in glob.glob("*.txt"): with open(file, "a") as f: f.write(" ") f.write(" ") f.close() 您可以只打印新行字符: import glob for fil

我有几个文本文件,需要在每个文件的最后添加两个额外的空行。下面的脚本在每个文本文件的最后一行添加一个空格。如何再添加一个空行?先谢谢你

  import glob
  for file in glob.glob("*.txt"):
      with open(file, "a") as f:
          f.write(" ")
          f.write(" ")
          f.close()

您可以只打印新行字符:

 import glob
  for file in glob.glob("*.txt"):
      with open(file, "a") as f:
          f.write("\n\n")
使用with语句时,不必手动关闭文件。Python将为您执行此操作。

f.write不会自动向文件中添加换行符,您必须自己添加换行符

另外,您不需要执行f.close,这是由with语句处理的

范例-

import glob
for file in glob.glob("*.txt"):
    with open(file, "a") as f:
        f.write("\n\n")

你不是在写一个空行,你是在写一个有空格的行。请尝试f.write'\n\n'。此-f.write\n