如果匹配,如何替换文件的字符串

2024-10-02 20:33:21 发布

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

我有两个输入和一个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")

Tags: txta2a1withfilenamebooksa3file
1条回答
网友
1楼 · 发布于 2024-10-02 20:33:21

第一种方法是在参数中插入要替换的内容(即本例中的pencil),然后使用replace()将“pencil”替换为“pen”,这样可以得到如下结果:

def func(filename,a,b,c):
    txt1,txt2="",""
    with open(filename,'r') as f:
        txt1 =f.readline().strip()
        while(txt1):
            if a==txt1[:len(a)]:
                txt1.replace(c,b)
            txt2+=txt1+'\n'
            txt1=f.readline().strip()
    with open(filename,'w') as f:
        f.write(txt2)

func("file.txt","A2","pen","pencil")

如果要替换为最后一个索引,请执行以下操作:

def func(filename,a,b):
    txt1,txt2="",""
    with open(filename,'r') as f:
        txt1 =f.readline().strip()
        while(txt1):
            if a==txt1[:len(a)]:
                x = txt1.split("|")[:-2] # take out first 2 ["A2","Color"]
                x.append(b) #add "pen" so now ["A2","Color","Pen"]
                txt1 = "|".join(x) #join them into string
                txt1 += "|" #Add another "|" at end of string
            txt2+=txt1+'\n'
            txt1=f.readline().strip()
    with open(filename,'w') as f:
        f.write(txt2)

func("file.txt","A2","pen")

相关问题 更多 >