Forums

After write to file the file is empty but it can read from it

It's my first time programming in Python and I'm trying to write a matrix inside a file based on a button grid (Tkinter).

from tkinter import *

class App():
    def __init__(self, root):
        self.root = root
        self.TopFrame = Frame(root)
        self.BottomFrame = Frame(root)
        self.TopFrame.grid(row=0)
        self.BottomFrame.grid(row=6)

    buttonQ = Button(self.BottomFrame, text="Quit", command=quit)
    buttonS = Button(self.BottomFrame, text="Save", command=self.saveToFile)
    buttonS.grid(row=0, column=0, padx=10)
    buttonQ.grid(row=0, column=1, padx=10)

def Function(self):
    self.grid = []
    for i in range(5):
        row = []
        for j in range(5):
            row.append(Button(self.TopFrame,width=6,height=3,command=lambda i=i, j=j: self.getClick(i, j),background='gray'))
            row[-1].grid(row=i,column=j)
        self.grid.append(row)

def getClick(self, i, j):
    orig_color = self.grid[i][j].cget('bg')
    if orig_color=="red":
        self.grid[i][j]["bg"]="gray"
    else:
        self.grid[i][j]["bg"]="red"

def saveToFile(self):
    myFile=open("example.txt", 'w')
    for line in range(5):
        for column in range(5):
            bg_color = self.grid[line][column].cget('bg')
            if bg_color == "red":
                myFile.write("1 ")
            else:
                myFile.write("0 ")
        myFile.write("\n")
    #myFile.flush()
    myFile.close()
    myFile = open("example.txt",'r')
    print(myFile.read())
    myFile.close()

root = Tk()
app = App(root)
app.Function()
root.mainloop()

The problem is that when I press the save button i should save a matrix in the example.txt file but when I open it it's empty and I don't know why :( But it reads from it the matrix and displays it in the console... What am I doing wrong? I'm running the code in Komodo Edit 10.2

::python

You're looking at some other file that also happens to be called example.txt. The file you're looking for will be in the working directory when you run the file, not in the same directory as your Python file.

You are right... I didn't know that. Thanks a lot! :)