Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...