'i wanna replace an old value with new in txt file with tkinter can u help ? nope and yeah are variables from input i transfered arguments to str

btn8 =Button(SignIn, width=7, height=2, text="Changer", bg="#3d3d3d", fg="white", borderwidth=0, command=lambda: change(nope, yeah)).grid(row=0, column=3)

SignIn.mainloop()

def change(old, new):

    with open("test.txt", 'r') as file:rgu
        data = file.read()         
        data = data.replace(old, new)

 
    with open("test.txt", 'w') as file:
      
        file.write(data)


Solution 1:[1]

Lets say you have a text file in the same location as your python file you could do something like this. You essentially rewrite all the contents to the text file and omit the value you want to remove.

file = "data.txt" #name of your text file
value = "1" #value you are removing
new_value = "88" #value you are adding

with open(file, "r") as q: #open file and read lines
    lines = q.readlines()
with open(file, "w") as q:
    for line in lines:
        if line.strip("\n") != value: #compare the contents to whatever you want to remove
            q.write(line) #write everything back except the value you want to remove
with open(file, "a") as x:
    x.write("\n" + new_value) #write your new value to the text file

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1