0
votes

I am trying to open a file, remove some characters (defined in dic) and then save it to the same the file. I can print the output and it looks fine, but I cannot save it into the same file that the original text is being loaded from.

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\n'%s'" % fname)
            return


if __name__ == "__main__":
    MyFrame().mainloop()

I have tried several commands but either I am receiving python errors or it is simply not working.

2

2 Answers

0
votes

Strings do not have a .write method. The following should work (I tried it): replace

data.write(data2)              #and here should it happen

with

myfile.seek(0)
myfile.truncate()
myfile.write(data2)

The truncate() call is needed if data2 is shorter than data as otherwise, the tail end of data will be left in the file.

1
votes

This is often implemented by writing to a temp file and then moving it to the original file's name.