简体   繁体   中英

How should i replace a word in a specific line in a file (python)

I have one file called tenantdetails(tdetails.txt) I want to replace one of the data inside but the other similar data I dont want them to be affected. This is my file:

T001,ly,0500505,male,17,johor,butterworth ,adam,long,
T002,ll,06060606,female,19,johor,kl,lili ,short,
T003,xh,030303,male,17,juru,hotel,adik,...,

So, this is my code:

def word_search(key, filename):
    with open(filename,"r") as file:  # opening the file using with to ensure it closes after the block of code is executed
        lines = file.readlines()  # reading the lines of the files in order
    for number, line in enumerate(lines, 1):  # using enumerate to map each line of the file to it's line_number
        if key in line:  # searching for the keyword in file
            return( number)  # returning the line number if the keyword

def replace_line(file,old,new):
    key=input("Enter keyword")
    line_num=word_search(key,file)
    print(line_num)

    filedata=''
    with open(file,"r") as f:
        for line in f:
            if old in line[line_num]:
                line= line.replace(old, new)
            filedata += line
    with open(file,"w") as f:
         f.write(filedata)

How should i change the Johor for T001, but T002 will not affected

Loop through every line and when the correct line is found loop through every word until the correct word is found.

I would recommend that instead of trying to edit the line in the file you completely rewrite the file with the edited line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM