gpt4 book ai didi

python - 如何将字符串写入特定行号?

转载 作者:太空宇宙 更新时间:2023-11-03 14:28:04 25 4
gpt4 key购买 nike

经过相当多的搜索,我很难找到这个问题的答案。我想要做的是,根据我的字符串搜索字符串并在其上方或下方的行中写入。

这是我到目前为止所做的事情:

file = open('input.txt', 'r+')  
f = enumerate(file)
for num, line in f:
if 'string' in line:
linewrite = num - 1
???????

编辑初始问题的扩展:我已经选择了最能解决我最初问题的答案。但是现在使用我重写文件的 Ashwini 方法,我该如何进行搜索并替换字符串。更具体地说。

我有一个文本文件

SAMPLE  
AB
CD
..
TYPES
AB
QP
PO
..
RUNS
AB
DE
ZY

我想用 XX 替换 ABONLY UNDER lines SAMPLERUNS我已经尝试过多种使用 replace() 的方法。我试过类似的东西

if  'SAMPLE' in line:  
f1.write(line.replace('testsample', 'XX'))
if 'RUNS' in line:
f1.write(line.replace('testsample', 'XX'))

那没用

最佳答案

以下内容可用作模板:

import fileinput

for line in fileinput.input('somefile', inplace=True):
if 'something' in line:
print 'this goes before the line'
print line,
print 'this goes after the line'
else:
print line, # just print the line anyway

关于python - 如何将字符串写入特定行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16879337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com