Home > front end >  search and replace using dictionary on files
search and replace using dictionary on files

Time:12-20

I am trying to write a program to read the input from a file a.txt

Hi this is nick, I am male and I am 30 years old.

and replace the name, age and gender of people and write it to a new file b.txt. Below is my try.

orig_file=open("a.txt","r") # file handle 
new_file=open("b.txt","w")    # new file handle
temp_buffer=orig_file.read()
lookup_dict={"nick":"andrea", "male":"female", "30":"20"}

for line in temp_buffer:
    for word in lookup_dict:
        line= line.replace(word, lookup_dict[word])
        new_file.write(line)

My expected result for b.txt is

Hi this is andrea, I am female and I am 20 years old.

observed output (b.txt)

HHHiii   ttthhhiiisss   iiisss   nnniiiccckkk,,,   III   aaammm   mmmaaallleee   aaannnddd   III   aaammm   333000   yyyeeeaaarrrsss   ooolllddd...

Could someone explain what I am doing wrong and correct me.

CodePudding user response:

Use readlines instead of read and call close() on the files manually, since you are not using with:

orig_file = open("a.txt", "r")  # file handle
new_file = open("b.txt", "w")  # new file handle
temp_buffer = orig_file.readlines()
orig_file.close()
lookup_dict = {"nick": "andrea", "male": "female", "30": "20"}
for line in temp_buffer:
    for word in lookup_dict:
        line = line.replace(word, lookup_dict[word])
    new_file.write(line)
new_file.close()

b.txt:

Hi this is andrea, I am female and I am 20 years old.
  • Related