Home > other >  i wanna replace an old value with new in txt file with tkinter can u help ? nope and yeah are variab
i wanna replace an old value with new in txt file with tkinter can u help ? nope and yeah are variab

Time:04-08

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)

CodePudding user response:

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
  • Related