我有两个输入和一个file.txt
file.txt包含以下行
A1|books|cloths|
A2|color|pencil|
A3|ball|
输入1,输入2
input1必须选择要添加的行(A1、A2或A3)
input2必须选择要添加的字符串
输入1=A2,输入2=pen
那么我期望的file.txt是
A1|books|cloths|
A2|color|pen|
A3|ball|
notice that pencil is replace with pen
下面的代码将添加到文件的最后一部分
def func(filename,a,b):
txt1,txt2="",""
with open(filename,'r') as f:
txt1 =f.readline().strip()
while(txt1):
if a==txt1[:len(a)]:
txt1+=b
txt2+=txt1+'\n'
txt1=f.readline().strip()
with open(filename,'w') as f:
f.write(txt2)
func("file.txt","A2","pen")
第一种方法是在参数中插入要替换的内容(即本例中的pencil),然后使用replace()将“pencil”替换为“pen”,这样可以得到如下结果:
如果要替换为最后一个索引,请执行以下操作:
相关问题 更多 >
编程相关推荐