如何在Python文件中首次出现字符串后编写新行和字符串

2024-09-30 18:18:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在Python中第一次出现字符串之后再写一行和字符串 例如,我的文本文件如下:

123456
example string<random>
asdfg
zxc
example string<random>

我想换成

123456
example string<random>
Python inputted string
asdfg
zxc
example string<random> <- Stays the same

Tags: the字符串stringexamplerandomsame文本文件zxc
1条回答
网友
1楼 · 发布于 2024-09-30 18:18:56

从文件中读取行

lines = []
with open(file_name, 'r') as f:
  for line in f:
    lines.append(line)

with open(file_name, 'w+') as f:
  flag = True
  for line in lines:
    f.write(line)
    if line.startswith("example string") and flag:
      f.write("what ever\n")
      flag = False

输入文件

123456
example string<random>
asdfg
zxc
example string<random>

输出文件

123456
example string<random>
what ever
asdfg
zxc
example string<random>

相关问题 更多 >