file - Appending a specific line after having found it in Python -


this question has answer here:

i writing function allows user content in specific line (in file), , replace part of content in line, , re-writes file on same line.

def editplayer():     print "what information edit?"     print "1- forname"     print "2- surname"     print "3- email address"     choice = int(raw_input(""))      f = open("persons.txt","r+")     in range(2): # number of type of information         if choice == i: #check if choice equal current running of             line[choice-1] = str(raw_input("enter new information: ")) #modify choice-1's element in line             linestr = line[0] + ";" + line[1] + ";" +  line[2] #makes list in string 

the above code works, i.e. if user edit player's email address, input change 3rd element in line, , linestr have information including modified email address in same order.

i stuck @ point need re-write linestr file on same line original one. file looks

joe;bloggs;j.bloggs@anemailaddress.com sarah;brown;s.brown@anemailaddress.com 

the problem occurs because when writing

f.write(linestr) 

the first line of file replaced, if modify sarah's second name (to stack) , write file, file

sarah;stack;s.brown@anemailaddress.com sarah;brown;s.brown@anemailaddress.com 

instead of how should look, i.e.:

joe;bloggs;j.bloggs@anemailaddress.com sarah;stack;s.brown@anemailaddress.com 

could lead me in right direction? appreciated. thank you

the way need this, , way programs - write temporary file correct output, replace original file. fool proof way.

here general logic:

  1. open input file, , temporary output file.
  2. read line input file:
    1. if matches replacement criteria, write new modified line temporary output file; otherwise write line output file as-is.
  3. once lines have been processes, close input file.
  4. delete input file.
  5. rename temporary file same name input file.

to implement in python:

import os  open('input.txt') i, open('output.txt', 'w') o:     line in i:        if line.startswith('replace me:'):            line = 'new line, replaced old line.\n'        o.write(line)  os.rename('output.txt', 'input.txt') 

Comments