overwriting a specific line in a txt file

Viewed 611

i am still new to python, i have tried this way to overwrite a line on a txt file

'''

answer =input("R/S/L/M:")

if answer == "R":
    print ("Racer")
    f=open('character.txt', 'w+')
    with open("character.txt") as file_in:
        lines = [1]
        for line in file_in:
            lines.append(line)
    amount=int(input("please enter the amount"))            
    f.write(answer )
    f.write("" + "-" + str(amount) + '\n\n')
    f.write("" + '\n')
    f.close()
elif answer == "S":
    print ("Sage")      
    f=open('character.txt', 'w+')
    with open("character.txt") as file_in:
        lines = [3]
        for line in file_in:
            lines.append(line)
    amount=int(input("please enter the amount"))            
    f.write(answer )
    f.write("" + "-" + str(amount) + '\n\n')
    f.write("" + '\n')
    f.close()

'''

it replaces all of the lines of text regardless on the txt file what i am trying to do is so when i select R it writes to the 1st line on the txt file, and when i select S it writes to the 3rd line on the txt file

i have tried now

'''

  if answer == "R":
    print ("Racer")
    f=open('character.txt', 'w+')
    with open("character.txt", "r+") as myfile:
        data = myfile.read()
        myfile.seek(0)
        amount=int(input("please enter the amount"))
        newData1=(answer + "" + "-" + str(amount) + '\n\n')
        myfile.write(newData1)
        myfile.truncate()
    f.close()

 elif answer == "S":
    print ("Sage")       
    f=open('character.txt', 'w+')
    with open("character.txt", "r+") as myfile:
        data = myfile.read(4)
        myfile.seek(4)
        amount=int(input("please enter the amount"))
        newData2=(answer + "" + "-" + str(amount) + '\n\n')
        myfile.write(newData)
        myfile.truncate(4)
    f.close()

'''

can someone please point me in the right direction

1 Answers

Your first approach was already near the solution, but there you are not selecting the 1st or 3rd line, you are just creating a list containing a 1 (lines = [1]. You first need to open the file. Then, you can use file.readlines which returns a list containing each line as one separate string, instead of file.read, which returns the whole file as one string. Then, you assign a new value to one specific line, open the same file again, but now in write mode, use file.writelines to write the list of lines back to the file, and that's it !

if answer == "R":
    print("Racer")
    with open("character.txt", "r") as f: # with automatically closes the file - no need to do so yourself
        lines = f.readlines()

    amount = input("please enter the amount") # no need to convert the amount to int first if you then convert it back  to string below       
    lines[0] = answer + "-" + amount
    with open("character.txt", "w") as f:
        f.writelines(lines)

I will let you adapt the code for the other answers yourself. Please note that you could save many lines of code if you would put the above in a function hat accepts a number (the line you want to overwrite) and a string (the answer).

You surely wondered why I put lines[0] = ... in the code. Well, we start counting from 1, but Python starts counting from 0 ! What you call the 1st line, is for Python the 0st, what you call the 2nd, is for Python the 1st. and so on.

And here some notes to your second approach: file.seek seeks to the byte in the file specified by the number you passed to it, not to the line. And file.truncate resizes the file. It does not overwrite the file.

Related