How can I save output tho the same file that I have got the data from, in Python 3
我试图打开一个文件,删除一些字符(在dic中定义),然后将其保存到同一个文件中。我可以打印输出,它看起来很好,但我不能将其保存到加载原始文本的同一个文件中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | from tkinter import * from tkinter.filedialog import askopenfilename from tkinter.messagebox import showerror import sys import fileinput dic = {'/':' ', '{3}':''}; def replace_all(text, dic): for i, j in dic.items(): text = text.replace(i, j) return text class MyFrame(Frame): def __init__(self): Frame.__init__(self) self.master.title("Example") self.master.rowconfigure(5, weight=1) self.master.columnconfigure(5, weight=1) self.grid(sticky=W+E+N+S) self.button = Button(self, text="Browse", command=self.load_file, width=10) self.button.grid(row=1, column=0, sticky=W) def load_file(self): fname = askopenfilename(filetypes=(("Napisy","*.txt"), ("All files","*.*") )) if fname: try: with open (fname, 'r+') as myfile: #here data = myfile.read() #here data2 = replace_all(data, dic) #here print(data2) #here data.write(data2) #and here should it happen except: showerror("Open Source File","Failed to read file '%s'" % fname) return if __name__ =="__main__": MyFrame().mainloop() |
我尝试了几个命令,但要么我收到了python错误,要么它根本不起作用。
这通常是通过写入一个临时文件,然后将其移动到原始文件的名称来实现的。
字符串没有.write方法。以下应该有效(我试过了):更换
1 | data.write(data2) #and here should it happen |
具有
1 2 3 | myfile.seek(0) myfile.truncate() myfile.write(data2) |
号
如果data2比数据短,则需要truncate()调用,否则,数据的尾部将保留在文件中。