Python Forum
[WxPython] Writing to files and using WxPython
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[WxPython] Writing to files and using WxPython
#1
Smile 
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!
Reply
#2
Also, sometimes it dosen't writes to the file very late like after 5 - 6 runs... Huh
Reply
#3
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.
Reply
#4
Yep I noticed that and corrected it! IT works now! Thanks!
Reply
#5
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.htm...Base.flush
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020