首页 > 解决方案 > 最后一个字符缺少python

问题描述

在一个特定的文件中,我想用给定的输入替换一个字符串。我使用 tkinter 提供输入

我有两个脚本,第一个是使用 tkinter 进行输入,第二个脚本是替换。

替换脚本:

import os
import linecache
line = linecache.getline("sele4.py", 27)

filename = "sele4.py" 
def read_file():
    with open("line.txt", "r") as f:
        first = f.read().splitlines()
    return first

#initial = read_file()
#print (initial)
while True:
    initial = read_file()
    current = read_file()
    if initial != current:
        for line in current:
            if line not in initial:
                print (line)

                filename = "sele4.py"
                filename1 = "dele.py"
                with open(filename, 'r') as fl:
                    content = fl.read().replace('Ricky',line)

                with open(filename, 'w') as fl:
                    fl.write(content)


                text2 = line[line.find("\'")+1:line.find("\' ")]
                #text = line.split("'")[1]
                text = text2.split("'", 1)[0]

                print (text)


                with open(filename1, 'r') as f:

                    content = f.read().replace('Ricky',text)

                with open(filename1, 'w') as f:
                    f.write(content)
                print ("done")


        initial = current

在上面的脚本中,我首先读取文件并开始一个无限循环,因为任何时候用户在 tkinter 中输入它应该替换然后它打开一个它必须替换的文件并稍后再次替换字符串它打开同一个文件和然后替换字符串,因此如果给出新输入,它可以再次工作,但是当它从 filename1 读取时,它会丢失最后一个字符。sele4.py 中的第 27 行是 "driver.find_element_by_xpath("//*[contains(text(), 'Ricky')]").click()"

from tkinter import *
root = Tk()
root.title('Ma')
#root.iconbitmap('c:/gui/codemy.ico')
root.geometry("500x400")

def open_txt():
        text_file = open("line.txt", 'r')
        stuff = text_file.read()


        my_text.insert(END, stuff)
        text_file.read()

def save_txt():
        text_file = open('line.txt','w')
        text_file.write(my_text.get(1.0, END))
my_text = Text(root, width=40,height=10,font=("Helvetica",16))
my_text.pack(pady=20)

open_button = Button(root, text="Open File", command=open_txt)
open_button.pack(pady=20)

save_button = Button(root, text="Save File", command=save_txt)
save_button.pack(pady=20)


root.mainloop()

首先我们需要运行 replace.py 点击打开文件并保存按钮然后运行 ​​tkinter 文件并查看在 replace.py 文件终端中的输出

实际输出:

point


poin


done

预期输出:

point


point


done

请让我知道我哪里出错了,以及是否有其他有效的方法可以做到这一点

标签: pythonpython-3.xtkinterfilesystemsinfinite-loop

解决方案


推荐阅读