gapi31
gapi31

Reputation: 27

Python - start writing into the second row of a text file

I want to start writing into the second row of my text file.

Here is what I currently have (but this starts at the bottom of the file):

predicted_inp = input("What did you expect answer should be?")
actions[a] = predicted_inp
f = open("training.txt", "a")
f.write(""+predicted_inp+"" + ':' + ""+a+""+",", file=f)[1]
f.close()

Dismiss the input filed and the second line.

Upvotes: 0

Views: 894

Answers (1)

Barmar
Barmar

Reputation: 780869

a is for appending to the end of a file.

Read the whole file into a list, replace the second element of the list, then write it all back out.

with open("training.txt", "r") as f:
    lines = f.readlines()
    lines[1] = f"{predicted_inp}:{a}\n"
with open("training.txt", "w") as f:
    f.writelines(lines)

Upvotes: 1

Related Questions