Appending a specific line after having found it in

2019-08-12 00:52发布

This question already has an answer here:

I am writing a function that allows a user to look for content in a specific line (in a file), and replace part of that content in that line, and re-writes it to the file on the same line.

def editPlayer():
    print "What information would you like to edit?"
    print "1- Forname"
    print "2- Surname"
    print "3- Email address"
    choice = int(raw_input(""))

    f = open("persons.txt","r+")
    for i in range(2): # number of type of information
        if choice == i: #check if choice equal current running of i
            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 a string

The above code works, i.e. if the user was to edit the player's email address, his input would change the 3rd element in line, and lineStr would have all the information including the modified email address in the same order.

I am stuck at the point where I need to re-write lineStr into my file on the same line as the original one. The file looks like so

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 the file will be replaced, so if I were to modify Sarah's second name (to Stack) and write it to the file, the file would look like

Sarah;Stack;s.brown@anemailaddress.com
Sarah;Brown;s.brown@anemailaddress.com

instead of how it should look, i.e.:

Joe;Bloggs;j.bloggs@anemailaddress.com
Sarah;Stack;s.brown@anemailaddress.com

Could anyone lead me in the right direction? Any help would be appreciated. Thank you

1条回答
爷的心禁止访问
2楼-- · 2019-08-12 01:44

The way you need to do this, and the way most programs do it - is to write a temporary file with the correct output, then replace the original file. This is the most fool proof way.

Here is the general logic:

  1. Open the input file, and a temporary output file.
  2. Read a line from the input file:
    1. If it matches the replacement criteria, write the new modified line to the temporary output file; otherwise write the line to the output file as-is.
  3. Once all lines have been processes, close the input file.
  4. Delete the input file.
  5. Rename the temporary file with the same name as the input file.

To implement it in Python:

import os

with open('input.txt') as i, open('output.txt', 'w') as o:
    for line in i:
       if line.startswith('Replace Me:'):
           line = 'New line, replaced the old line.\n'
       o.write(line)

os.rename('output.txt', 'input.txt')
查看更多
登录 后发表回答