From 05ac589e2daeaf5c81ad80aa210b17be70d275c7 Mon Sep 17 00:00:00 2001 From: "Per A. Brodtkorb" Date: Fri, 20 Mar 2020 15:03:09 +0100 Subject: [PATCH] Fixes issue 1555 Replace open-close statements by the use of "with"-blocks. With the "With" statement, you get better syntax and exceptions handling. "The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks." In addition, it will automatically close the file. The with statement provides a way for ensuring that a clean-up is always used. --- wx/py/frame.py | 34 ++++++++++++++-------------------- 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/wx/py/frame.py b/wx/py/frame.py index 249ef039..e3c7aaf1 100644 --- a/wx/py/frame.py +++ b/wx/py/frame.py @@ -839,16 +839,12 @@ class ShellFrameMixin: def SaveHistory(self): if self.dataDir: try: - name = os.path.join(self.dataDir, 'history') - f = open(name, 'wb') - hist = [] enc = 'utf-8' - for h in self.shell.history: - h = h.encode(enc) - hist.append(h) - hist = b'\x00\n'.join(hist) - f.write(hist) - f.close() + hist = b'\x00\n'.join([h.encode(enc) + for h in self.shell.history]) + name = os.path.join(self.dataDir, 'history') + with open(name, 'wb') as f: + f.write(hist) except: d = wx.MessageDialog(self, "Error saving history file.", "Error", wx.ICON_EXCLAMATION|wx.OK) @@ -861,9 +857,9 @@ class ShellFrameMixin: name = os.path.join(self.dataDir, 'history') if os.path.exists(name): try: - f = open(name, 'rb') - hist = f.read() - f.close() + with open(name, 'rb') as f: + hist = f.read() + enc = 'utf-8' hist = [h.decode(enc) for h in hist.split(b'\x00\n')] self.shell.history = hist @@ -908,9 +904,8 @@ class ShellFrameMixin: ## d.Destroy() try: - f = open(fileName, "w") - f.write(text) - f.close() + with open(fileName, "w") as f: + f.write(text) except: d = wx.MessageDialog(self, u'Error saving session',u'Error', wx.OK | wx.ICON_ERROR) @@ -923,8 +918,8 @@ class ShellFrameMixin: import io # Use newline=None to translate \n \r \r\n to \n on read. The # old-style mode='U' is deprecated. - text = io.open(self.startupScript, 'r', - newline=None, encoding='utf-8').read() + with io.open(self.startupScript, 'r', newline=None, encoding='utf-8') as fid: + text = fid.read() else: text = '' @@ -932,9 +927,8 @@ class ShellFrameMixin: if dlg.ShowModal() == wx.ID_OK: text = dlg.GetText() try: - f = open(self.startupScript, 'wb') - f.write(text.encode('utf-8')) - f.close() + with open(self.startupScript, 'wb') as f: + f.write(text.encode('utf-8')) except: d = wx.MessageDialog(self, "Error saving startup file.", "Error", wx.ICON_EXCLAMATION|wx.OK)