如何在Python中的特定行下远程添加行

如何在Python中的特定行下远程添加行,python,Python,我有一个.py文件: some imports #TypeA var_1 = ("some code...") var_2 = ("some code...") ... #TypeB var_3 = ("some code...") var_4 = ("some code...") 我想在#TypeA下加一行,在#TypeB下加一行,等等。 我现在得到的是: with open('file.py', 'r+')

我有一个.py文件:

some imports

#TypeA
var_1 = ("some code...")
var_2 = ("some code...")
...
#TypeB
var_3 = ("some code...")
var_4 = ("some code...")
我想在#TypeA下加一行,在#TypeB下加一行,等等。 我现在得到的是:

with open('file.py', 'r+') as file:
file_content = file.readlines()

file_content.insert(1,'var_0 = ("some code...")\n')
但是这里我必须声明具体的行。

您可以使用for循环搜索#TypeA

i = 0
for line in file_content:
    if line.strip() == "#TypeA":
        file_content.insert(i+1, "var_0 = ('some code...')\n")
        break
    i += 1
您可以使用for循环搜索#TypeA

i = 0
for line in file_content:
    if line.strip() == "#TypeA":
        file_content.insert(i+1, "var_0 = ('some code...')\n")
        break
    i += 1

通过filecontent循环查找TypeA和TypeB的索引如何

TypeAIndex = 0
for i in file_content:
    if "# TypeA" in i:
        TypeAIndex = i
        break

这个例子可以稍加润色,但它应该给你一个想法。

通过文件内容循环找到TypeA和TypeB的索引怎么样

TypeAIndex = 0
for i in file_content:
    if "# TypeA" in i:
        TypeAIndex = i
        break
这个例子可能需要一些润色,但它应该会给你一个想法。

步骤可能是

  • 读文件
  • 查找
    键入A
    并插入新行
  • 查找
    类型B
    并插入新行
  • 在开始处重置文件光标(以避免追加)
  • 写台词
步骤可能是

  • 读文件
  • 查找
    键入A
    并插入新行
  • 查找
    类型B
    并插入新行
  • 在开始处重置文件光标(以避免追加)
  • 写台词

如何在不指定要在哪一行的情况下在某处添加代码行?您可以找到TypeA和TypeB的索引,这会更容易。是否要将该行插入实际文件中,或者仅仅是内存中的内容列表?如何在不指定要在哪一行的情况下在某处添加一行代码?您可以找到TypeA和TypeB的索引,这会更容易。您是要将该行插入实际文件中,还是只插入内存中的内容列表?