[WxPython] Writing to files and using WxPython - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: GUI (https://python-forum.io/forum-10.html) +--- Thread: [WxPython] Writing to files and using WxPython (/thread-31493.html) |
Writing to files and using WxPython - TheUNOGuy - Dec-15-2020 Hello everyone! This is my first post here! I have a problem with wxpython and file handling at the same time...I have made a small text editor and after I write in the text box and click save, it's saving after I run the program 1 - 2 times again...How can I save as soon as I click save? My program: import wx fil = open ( "E:\Text Editor\Files\File1.txt", "r+" ) class MyFrame ( wx.Frame ): def __init__( self ): super().__init__ ( parent = None, title = 'Editor' ) panel = wx.Panel ( self ) sizer = wx.BoxSizer ( wx.VERTICAL ) self.text_ctrl = wx.TextCtrl ( panel, pos = ( 10, 10 ) ) sizer.Add ( self.text_ctrl, 1, wx.ALL | wx.EXPAND, 10 ) panel.SetSizer(sizer) menubar = wx.MenuBar() fileMenu = wx.Menu() menubar.Append ( fileMenu, '&File' ) m1 = fileMenu.Append ( wx.ID_SAVE, 'Save' ) self.Bind ( wx.EVT_MENU, self.OnSave, m1 ) m2 = fileMenu.Append ( wx.ID_EXIT, 'Quit' ) self.Bind ( wx.EVT_MENU, self.OnQuit, m2 ) self.text_ctrl.WriteText( fil.read() ) self.SetMenuBar ( menubar ) self.Show() def OnSave ( self, event ): text = self.text_ctrl.GetValue() fil.write ( str ( text ) ) print ( "Saved file") def OnQuit ( self, event ): print ( "Closed" ) self.Close() if __name__ == '__main__': app = wx.App() frame = MyFrame() app.MainLoop()Any help will be appreciated! Thanks! RE: Writing to files and using WxPython - TheUNOGuy - Dec-15-2020 Also, sometimes it dosen't writes to the file very late like after 5 - 6 runs... RE: Writing to files and using WxPython - deanhystad - Dec-15-2020 You should not leave the file open. When reading a file into your editor open the file for reading, read the contents, close the file. When you want to save your text to a file open the file for writing, save the file, close the file. RE: Writing to files and using WxPython - TheUNOGuy - Dec-16-2020 Yep I noticed that and corrected it! IT works now! Thanks! RE: Writing to files and using WxPython - Larz60+ - Dec-16-2020 you can also flush a files buffers at any time, which forces a physical write of the data. see: https://docs.python.org/3/library/io.html#io.IOBase.flush |