无论如何,您基本上不能只在文件中间插入一行。相反,您应该使用包含新行的新文件覆盖旧文件。所以解决方案是这样的:
- 打开文件进行阅读。
- 保存文件的内容,最好是逐行保存,以便更容易插入到特定行。
- 将新行插入保存的内容中。
- 重新打开文件,这次是在写入模式下,并用保存的修改内容覆盖其内容。
因此,对于您的示例,并使用您的标志想法来查找插入点,您将执行以下操作:
#Step 1
with open('testFile', 'r') as f:
#Step 2
contentList = f.readlines()
#Step 3
isJane = False # <-- flag
i = 0
insertIndex = None # used to avoid changing the list while looping over it
for line in contentList:
if 'jane' in line.lower():
isJane = True
if isJane and line.strip() == '?':
insertIndex = i
i += 1
contentList.insert(insertIndex, 'fourth shift\n')
#Step 4
with open('testFile', 'w') as f:
f.writelines(contentList)
有更短的方法可以做到这一点,但这可能是最直接的。