I have a txt file with content as below: name password number location
the four items are separated into each line
I would like to change the content in the specific line, eg: change the third line("number") to "phone number"
Problem I faced is not replacing the "number", "number" still there, and the "phone number" is appended at the last line
Output:
name
password
number
location
phone number
How should I fix the code, so it can replace the content in certain line?
Below is my code
userID = 1
print("Modify: ")
print("1. Username")
print("2. Password")
print("3. Contact number")
print("4. Location")
print()
print("Enter 'main' to back to main screen")
select = int(input())
change = input("Change to: ")
if select != 'main:':
if int(select) <= 4:
#save to individual file
fhand = open("user_"+str(userID)+".txt",'r+')
lineNo = 0 #line number
for line in fhand():
lineNo = lineNo + 1
if lineNo == select:
fhand.write(line.replace(line, change)) #replace the content
print()
print("Changed to:", change)
print("Change successful")
print("\n Bring you back to <customer main menu>")
fhand.close()
I tried counting the line number, then when the line number reach the selection of the user, it starts to replace the line, and it doesn't work
Thanks for the helps