Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

tkinter - Replace nth line in file in Python

I want to replace nth line in the txt file with whatever i type in tkinter:

from tkinter import *
root = Tk()

e1=Entry(root)
e1.grid(row=0, column=0)


old_line=open("my_file.txt","r").readlines()[2]

def replace_old_line():
    f=open("my_file.txt","r")
    read=f.read()
    read1=read.replace(old_line, str(e1.get()))
    print(read1)
Button(root, text="type_and_click_to_replace", command=replace_old_line).grid(row=1, column=0)

root.mainloop() 

But if my initial file consists of:

London
New-York
LA
Tokyo

and I want to replace LA with whatever i type in tkinter (for example AMERICA) i get

London
New-York
AMERICATokyo

As you see line (Tokyo) jumped up... how to make it not move at all?

I think this is very basic it needs some somewhere but i am stuck in this seemingly ease thing ... sorry for such a simple question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...