在第一行中为python中的多个文本文件添加一个空格

问题描述 投票:0回答:2

我有53个文本文件。XXXX_1,共53XXXX_2,共53XXXX_3,共53XXXX_4,共53。。。XXXX_53 of 53

每个文件都没有空白。我想编写一个用于在第一行中添加空格并重新写入的代码(输入,而不是空格键)

python add blank-line
2个回答
0
投票

这里是一个可以满足您目的的链接。

Prepend a line to an existing file in Python

理想情况下,您必须

  1. 一次打开一个现有文件
  2. 用第一行写一个新文件,即\n(这是新行)
  3. 然后迭代(逐行)读取现有文件并将内容写入新文件

重复此操作,直到完成所有文件的处理。

我可以轻松地为您编写此代码,但这对您的智慧是不公正的,因此我将让您编写并为您解决问题提供任何帮助。

希望对您有用。


0
投票

您可以这样操作:

list_of_filenames=['f1','f2'....] #edit this list and add all the 53 file names here
for x in range(53):
    f = open(list_of_filenames[x], "r")
    contents = f.readlines()
    f.close()

    contents.insert(0, '\n')

    f = open(list_of_filenames[x], "w")
    contents = "".join(contents)
    f.write(contents)
    f.close()
© www.soinside.com 2019 - 2024. All rights reserved.