Wed, 14 Oct 2020 17:50:39 +0200
Changed code to use context manager 'open()' for file operations.
--- a/eric6/CondaInterface/CondaExportDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/CondaInterface/CondaExportDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -183,9 +183,8 @@ return try: - f = open(fileName, "w") - f.write(self.requirementsEdit.toPlainText()) - f.close() + with open(fileName, "w") as f: + f.write(self.requirementsEdit.toPlainText()) except (OSError, IOError) as err: E5MessageBox.critical( self,
--- a/eric6/Cooperation/ChatWidget.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Cooperation/ChatWidget.py Wed Oct 14 17:50:39 2020 +0200 @@ -573,9 +573,8 @@ fname = Utilities.toNativeSeparators(fname) try: - f = open(fname, "w", encoding="utf-8") - f.write(txt) - f.close() + with open(fname, "w", encoding="utf-8") as f: + f.write(txt) except IOError as err: E5MessageBox.critical( self,
--- a/eric6/DataViews/PyProfileDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/DataViews/PyProfileDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -240,9 +240,8 @@ self.close() return try: - f = open(fname, 'rb') - self.stats = pickle.load(f) # secok - f.close() + with open(fname, 'rb') as f: + self.stats = pickle.load(f) # secok except (EnvironmentError, pickle.PickleError, EOFError): E5MessageBox.critical( self,
--- a/eric6/DebugClients/Python/DebugClientBase.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/DebugClients/Python/DebugClientBase.py Wed Oct 14 17:50:39 2020 +0200 @@ -220,11 +220,10 @@ else: default = 'utf-8' try: - f = open(filename, 'rb') - # read the first and second line - text = f.readline() - text = "{0}{1}".format(text, f.readline()) - f.close() + with open(filename, 'rb') as f: + # read the first and second line + text = f.readline() + text = "{0}{1}".format(text, f.readline()) except IOError: self.__coding = default return
--- a/eric6/DebugClients/Python/PyProfile.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/DebugClients/Python/PyProfile.py Wed Oct 14 17:50:39 2020 +0200 @@ -52,14 +52,12 @@ return try: - cache = open(self.timingCache, 'rb') - timings = marshal.load(cache) # secok - if isinstance(timings, dict): - self.timings = timings + with open(self.timingCache, 'rb') as cache: + timings = marshal.load(cache) # secok + if isinstance(timings, dict): + self.timings = timings except (EnvironmentError, EOFError, ValueError, TypeError): pass - finally: - cache.close() def save(self): """ @@ -67,12 +65,10 @@ """ # dump the raw timing data try: - cache = open(self.timingCache, 'wb') - marshal.dump(self.timings, cache) + with open(self.timingCache, 'wb') as cache: + marshal.dump(self.timings, cache) except EnvironmentError: pass - finally: - cache.close() # dump the profile data self.dump_stats(self.profileCache) @@ -83,14 +79,12 @@ @param file name of the file to write to (string) """ + self.create_stats() try: - f = open(file, 'wb') - self.create_stats() - pickle.dump(self.stats, f, 4) + with open(file, 'wb') as f: + pickle.dump(self.stats, f, 4) except (EnvironmentError, pickle.PickleError): pass - finally: - f.close() def erase(self): """
--- a/eric6/Debugger/CallStackViewer.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Debugger/CallStackViewer.py Wed Oct 14 17:50:39 2020 +0200 @@ -178,13 +178,12 @@ fname = Utilities.toNativeSeparators(fname) try: - f = open(fname, "w", encoding="utf-8") - itm = self.topLevelItem(0) - while itm is not None: - f.write("{0}\n".format(itm.text(0))) - f.write(78 * "=" + "\n") - itm = self.itemBelow(itm) - f.close() + with open(fname, "w", encoding="utf-8") as f: + itm = self.topLevelItem(0) + while itm is not None: + f.write("{0}\n".format(itm.text(0))) + f.write(78 * "=" + "\n") + itm = self.itemBelow(itm) except IOError as err: E5MessageBox.critical( self,
--- a/eric6/Debugger/CallTraceViewer.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Debugger/CallTraceViewer.py Wed Oct 14 17:50:39 2020 +0200 @@ -166,19 +166,18 @@ fname = Utilities.toNativeSeparators(fname) try: - f = open(fname, "w", encoding="utf-8") - itm = self.callTrace.topLevelItem(0) - while itm is not None: - isCall = itm.data(0, Qt.UserRole) - if isCall: - call = "->" - else: - call = "<-" - f.write("{0} {1} || {2}\n".format( - call, - itm.text(1), itm.text(2))) - itm = self.callTrace.itemBelow(itm) - f.close() + with open(fname, "w", encoding="utf-8") as f: + itm = self.callTrace.topLevelItem(0) + while itm is not None: + isCall = itm.data(0, Qt.UserRole) + if isCall: + call = "->" + else: + call = "<-" + f.write("{0} {1} || {2}\n".format( + call, + itm.text(1), itm.text(2))) + itm = self.callTrace.itemBelow(itm) except IOError as err: E5MessageBox.critical( self,
--- a/eric6/DocumentationTools/IndexGenerator.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/DocumentationTools/IndexGenerator.py Wed Oct 14 17:50:39 2020 +0200 @@ -180,9 +180,8 @@ ) + self.footerTemplate ) - f = open(filename, "w", encoding="utf-8", newline=newline) - f.write(doc) - f.close() + with open(filename, "w", encoding="utf-8", newline=newline) as f: + f.write(doc) return filename
--- a/eric6/DocumentationTools/QtHelpGenerator.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/DocumentationTools/QtHelpGenerator.py Wed Oct 14 17:50:39 2020 +0200 @@ -244,10 +244,9 @@ } txt = self.__convertEol(HelpProject.format(**helpAttribs), newline) - f = open(os.path.join(self.outputDir, HelpProjectFile), "w", - encoding="utf-8", newline=newline) - f.write(txt) - f.close() + with open(os.path.join(self.outputDir, HelpProjectFile), "w", + encoding="utf-8", newline=newline) as f: + f.write(txt) if ( self.createCollection and @@ -260,10 +259,9 @@ txt = self.__convertEol( HelpCollection.format(**collectionAttribs), newline) - f = open(os.path.join(self.outputDir, HelpCollectionProjectFile), - "w", encoding="utf-8", newline=newline) - f.write(txt) - f.close() + with open(os.path.join(self.outputDir, HelpCollectionProjectFile), + "w", encoding="utf-8", newline=newline) as f: + f.write(txt) sys.stdout.write("QtHelp files written.\n") sys.stdout.write("Generating QtHelp documentation...\n")
--- a/eric6/E5Gui/E5MainWindow.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/E5Gui/E5MainWindow.py Wed Oct 14 17:50:39 2020 +0200 @@ -48,9 +48,8 @@ # step 2: set a style sheet if styleSheetFile: try: - f = open(styleSheetFile, "r", encoding="utf-8") - styleSheet = f.read() - f.close() + with open(styleSheetFile, "r", encoding="utf-8") as f: + styleSheet = f.read() except (IOError, OSError) as msg: E5MessageBox.warning( self,
--- a/eric6/Graphics/UMLDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Graphics/UMLDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -254,9 +254,8 @@ lines.extend(self.umlView.getPersistenceData()) try: - f = open(filename, "w", encoding="utf-8") - f.write("\n".join(lines)) - f.close() + with open(filename, "w", encoding="utf-8") as f: + f.write("\n".join(lines)) except (IOError, OSError) as err: E5MessageBox.critical( self, @@ -284,9 +283,8 @@ return False try: - f = open(filename, "r", encoding="utf-8") - data = f.read() - f.close() + with open(filename, "r", encoding="utf-8") as f: + data = f.read() except (IOError, OSError) as err: E5MessageBox.critical( self,
--- a/eric6/MicroPython/MicroPythonGraphWidget.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/MicroPython/MicroPythonGraphWidget.py Wed Oct 14 17:50:39 2020 +0200 @@ -317,10 +317,9 @@ fileName = "{0}.csv".format(time.strftime("%Y%m%d-%H%M%S")) fullPath = os.path.join(dataDir, fileName) try: - csvFile = open(fullPath, "w") - csvWriter = csv.writer(csvFile) - csvWriter.writerows(self.__rawData) - csvFile.close() + with open(fullPath, "w") as csvFile: + csvWriter = csv.writer(csvFile) + csvWriter.writerows(self.__rawData) self.__dirty = False return True
--- a/eric6/Network/IRC/IrcChannelWidget.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Network/IRC/IrcChannelWidget.py Wed Oct 14 17:50:39 2020 +0200 @@ -1398,9 +1398,8 @@ txt = self.messages.toHtml() else: txt = self.messages.toPlainText() - f = open(fname, "w", encoding="utf-8") - f.write(txt) - f.close() + with open(fname, "w", encoding="utf-8") as f: + f.write(txt) except IOError as err: E5MessageBox.critical( self,
--- a/eric6/Network/IRC/IrcNetworkWidget.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Network/IRC/IrcNetworkWidget.py Wed Oct 14 17:50:39 2020 +0200 @@ -452,9 +452,8 @@ txt = self.messages.toHtml() else: txt = self.messages.toPlainText() - f = open(fname, "w", encoding="utf-8") - f.write(txt) - f.close() + with open(fname, "w", encoding="utf-8") as f: + f.write(txt) except IOError as err: E5MessageBox.critical( self,
--- a/eric6/PipInterface/Pip.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/PipInterface/Pip.py Wed Oct 14 17:50:39 2020 +0200 @@ -458,9 +458,8 @@ requirements, _user = dlg.getData() if requirements and os.path.exists(requirements): try: - f = open(requirements, "r") - reqs = f.read().splitlines() - f.close() + with open(requirements, "r") as f: + reqs = f.read().splitlines() except (OSError, IOError): return
--- a/eric6/PipInterface/PipFreezeDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/PipInterface/PipFreezeDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -196,9 +196,8 @@ return try: - f = open(fileName, "w") - f.write(self.requirementsEdit.toPlainText()) - f.close() + with open(fileName, "w") as f: + f.write(self.requirementsEdit.toPlainText()) except (OSError, IOError) as err: E5MessageBox.critical( self,
--- a/eric6/PipInterface/PipPackagesWidget.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/PipInterface/PipPackagesWidget.py Wed Oct 14 17:50:39 2020 +0200 @@ -1147,9 +1147,8 @@ if not os.path.exists(cfgFile): try: - f = open(cfgFile, "w") - f.write("[global]\n") - f.close() + with open(cfgFile, "w") as f: + f.write("[global]\n") except (IOError, OSError): # ignore these pass
--- a/eric6/PluginManager/PluginInstallDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/PluginManager/PluginInstallDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -464,18 +464,16 @@ d = os.path.dirname(outname) if not os.path.exists(d): self.__makedirs(d) - f = open(outname, "wb") - f.write(zipFile.read(name)) - f.close() + with open(outname, "wb") as f: + f.write(zipFile.read(name)) self.__installedFiles.append(outname) self.progress.setValue(tot) # now compile user interface files compileUiFiles(os.path.join(destination, packageName), True) else: outname = os.path.join(destination, pluginFileName) - f = open(outname, "w", encoding="utf-8") - f.write(pluginSource) - f.close() + with open(outname, "w", encoding="utf-8") as f: + f.write(pluginSource) self.__installedFiles.append(outname) except os.error as why: self.__rollback()
--- a/eric6/PluginManager/PluginManager.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/PluginManager/PluginManager.py Wed Oct 14 17:50:39 2020 +0200 @@ -206,8 +206,8 @@ fname = os.path.join(path, "__init__.py") if not os.path.exists(fname): try: - f = open(fname, "w") - f.close() + with open(fname, "w"): + pass except IOError: return ( False, @@ -219,8 +219,8 @@ if not os.path.exists(self.pluginDirs["user"]): os.mkdir(self.pluginDirs["user"], 0o755) try: - f = open(fname, "w") - f.close() + with open(fname, "w"): + pass except IOError: del self.pluginDirs["user"] @@ -231,13 +231,12 @@ # create the global plugins directory os.mkdir(self.pluginDirs["global"], 0o755) fname = os.path.join(self.pluginDirs["global"], "__init__.py") - f = open(fname, "w", encoding="utf-8") - f.write('# -*- coding: utf-8 -*-' + "\n") - f.write("\n") - f.write('"""' + "\n") - f.write('Package containing the global plugins.' + "\n") - f.write('"""' + "\n") - f.close() + with open(fname, "w", encoding="utf-8") as f: + f.write('# -*- coding: utf-8 -*-' + "\n") + f.write("\n") + f.write('"""' + "\n") + f.write('Package containing the global plugins.' + "\n") + f.write('"""' + "\n") if not os.path.exists(self.pluginDirs["global"]): del self.pluginDirs["global"]
--- a/eric6/Plugins/PluginWizardEricPlugin.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/PluginWizardEricPlugin.py Wed Oct 14 17:50:39 2020 +0200 @@ -166,8 +166,8 @@ packageFile = os.path.join(packagePath, "__init__.py") if not os.path.exists(packageFile): try: - f = open(packageFile, "w", encoding="utf-8") - f.close() + with open(packageFile, "w", encoding="utf-8"): + pass except IOError as err: E5MessageBox.critical( self,
--- a/eric6/Plugins/VcsPlugins/vcsGit/ConfigurationPage/GitPage.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsGit/ConfigurationPage/GitPage.py Wed Oct 14 17:50:39 2020 +0200 @@ -94,11 +94,10 @@ firstName, lastName, email = ( "Firstname", "Lastname", "email_address") try: - f = open(cfgFile, "w") - f.write("[user]\n") - f.write(" name = {0} {1}\n".format(firstName, lastName)) - f.write(" email = {0}\n".format(email)) - f.close() + with open(cfgFile, "w") as f: + f.write("[user]\n") + f.write(" name = {0} {1}\n".format(firstName, lastName)) + f.write(" email = {0}\n".format(email)) except (IOError, OSError): # ignore these pass
--- a/eric6/Plugins/VcsPlugins/vcsGit/GitDiffDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsGit/GitDiffDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -340,10 +340,9 @@ eol = e5App().getObject("Project").getEolString() try: - f = open(fname, "w", encoding="utf-8", newline="") - f.write(eol.join(self.contents2.toPlainText().splitlines())) - f.write(eol) - f.close() + with open(fname, "w", encoding="utf-8", newline="") as f: + f.write(eol.join(self.contents2.toPlainText().splitlines())) + f.write(eol) except IOError as why: E5MessageBox.critical( self, self.tr('Save Diff'),
--- a/eric6/Plugins/VcsPlugins/vcsGit/GitLogBrowserDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsGit/GitLogBrowserDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -2305,10 +2305,9 @@ eol = e5App().getObject("Project").getEolString() try: - f = open(fname, "w", encoding="utf-8", newline="") - f.write(eol.join(self.diffEdit.toPlainText().splitlines())) - f.write(eol) - f.close() + with open(fname, "w", encoding="utf-8", newline="") as f: + f.write(eol.join(self.diffEdit.toPlainText().splitlines())) + f.write(eol) except IOError as why: E5MessageBox.critical( self, self.tr('Save Diff'),
--- a/eric6/Plugins/VcsPlugins/vcsGit/GitStatusDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsGit/GitStatusDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -1148,9 +1148,8 @@ if patch: patchFile = self.__tmpPatchFileName() try: - f = open(patchFile, "w") - f.write(patch) - f.close() + with open(patchFile, "w") as f: + f.write(patch) self.vcs.gitApply(self.dname, patchFile, cached=True, noDialog=True) self.on_refreshButton_clicked() @@ -1171,9 +1170,8 @@ if patch: patchFile = self.__tmpPatchFileName() try: - f = open(patchFile, "w") - f.write(patch) - f.close() + with open(patchFile, "w") as f: + f.write(patch) self.vcs.gitApply(self.dname, patchFile, cached=True, reverse=True, noDialog=True) self.on_refreshButton_clicked() @@ -1204,9 +1202,8 @@ if patch: patchFile = self.__tmpPatchFileName() try: - f = open(patchFile, "w") - f.write(patch) - f.close() + with open(patchFile, "w") as f: + f.write(patch) self.vcs.gitApply(self.dname, patchFile, reverse=True, noDialog=True) self.on_refreshButton_clicked()
--- a/eric6/Plugins/VcsPlugins/vcsGit/git.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsGit/git.py Wed Oct 14 17:50:39 2020 +0200 @@ -1400,10 +1400,9 @@ if res: try: # create a .gitignore file - ignore = open(ignoreName, "w") - ignore.write("\n".join(ignorePatterns)) - ignore.write("\n") - ignore.close() + with open(ignoreName, "w") as ignore: + ignore.write("\n".join(ignorePatterns)) + ignore.write("\n") status = True except IOError: status = False @@ -1627,9 +1626,9 @@ name2 = "{0} (rev. {1})".format(name, rev2) else: try: - f1 = open(name, "r", encoding="utf-8") - output2 = f1.read() - f1.close() + with open(name, "r", encoding="utf-8") as f1: + output2 = f1.read() + f1.close() name2 = "{0} (Work)".format(name) except IOError: E5MessageBox.critical( @@ -2663,9 +2662,8 @@ self.__lastReplayPath = os.path.dirname(fname) try: - f = open(fname, "w") - f.write(output) - f.close() + with open(fname, "w") as f: + f.write(output) except (OSError, IOError) as err: E5MessageBox.critical( self.__ui, @@ -3579,8 +3577,8 @@ if not os.path.exists(cfgFile): # create an empty one try: - cfg = open(cfgFile, "w") - cfg.close() + with open(cfgFile, "w"): + pass except IOError: pass self.repoEditor = MiniEditor(cfgFile, "Properties") @@ -3601,11 +3599,10 @@ firstName, lastName, email = ( "Firstname", "Lastname", "email_address") try: - f = open(cfgFile, "w") - f.write("[user]\n") - f.write(" name = {0} {1}\n".format(firstName, lastName)) - f.write(" email = {0}\n".format(email)) - f.close() + with open(cfgFile, "w") as f: + f.write("[user]\n") + f.write(" name = {0} {1}\n".format(firstName, lastName)) + f.write(" email = {0}\n".format(email)) except (IOError, OSError): # ignore these pass @@ -3886,9 +3883,8 @@ return [] try: - modulesFile = open(submodulesFile, "r") - contents = modulesFile.readlines() - modulesFile.close() + with open(submodulesFile, "r") as modulesFile: + contents = modulesFile.readlines() except OSError: # silently ignore them return []
--- a/eric6/Plugins/VcsPlugins/vcsMercurial/HgDiffDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsMercurial/HgDiffDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -239,9 +239,8 @@ eol = e5App().getObject("Project").getEolString() try: - f = open(fname, "w", encoding="utf-8", newline="") - f.write(eol.join(self.contents.toPlainText().splitlines())) - f.close() + with open(fname, "w", encoding="utf-8", newline="") as f: + f.write(eol.join(self.contents.toPlainText().splitlines())) except IOError as why: E5MessageBox.critical( self, self.tr('Save Diff'),
--- a/eric6/Plugins/VcsPlugins/vcsMercurial/HgLogBrowserDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsMercurial/HgLogBrowserDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -2667,9 +2667,8 @@ eol = e5App().getObject("Project").getEolString() try: - f = open(fname, "w", encoding="utf-8", newline="") - f.write(eol.join(self.diffEdit.toPlainText().splitlines())) - f.close() + with open(fname, "w", encoding="utf-8", newline="") as f: + f.write(eol.join(self.diffEdit.toPlainText().splitlines())) except IOError as why: E5MessageBox.critical( self, self.tr('Save Diff'),
--- a/eric6/Plugins/VcsPlugins/vcsMercurial/HisteditExtension/HgHisteditCommitEditor.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsMercurial/HisteditExtension/HgHisteditCommitEditor.py Wed Oct 14 17:50:39 2020 +0200 @@ -49,9 +49,8 @@ populate the dialog. """ try: - f = open(self.__fileName, "r") - txt = f.read() - f.close() + with open(self.__fileName, "r") as f: + txt = f.read() except (IOError, OSError) as err: E5MessageBox.critical( self, @@ -89,9 +88,8 @@ """ msg = self.messageEdit.toPlainText() try: - f = open(self.__fileName, "w") - f.write(msg) - f.close() + with open(self.__fileName, "w") as f: + f.write(msg) except (IOError, OSError) as err: E5MessageBox.critical( self,
--- a/eric6/Plugins/VcsPlugins/vcsMercurial/HisteditExtension/HgHisteditPlanEditor.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsMercurial/HisteditExtension/HgHisteditPlanEditor.py Wed Oct 14 17:50:39 2020 +0200 @@ -103,9 +103,8 @@ populate the dialog. """ try: - f = open(self.__fileName, "r") - txt = f.read() - f.close() + with open(self.__fileName, "r") as f: + txt = f.read() except (IOError, OSError) as err: E5MessageBox.critical( self, @@ -239,9 +238,8 @@ """ text = self.__assembleEditPlan() try: - f = open(self.__fileName, "w") - f.write(text) - f.close() + with open(self.__fileName, "w") as f: + f.write(text) except (IOError, OSError) as err: E5MessageBox.critical( self,
--- a/eric6/Plugins/VcsPlugins/vcsMercurial/hg.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsMercurial/hg.py Wed Oct 14 17:50:39 2020 +0200 @@ -1708,9 +1708,8 @@ name2 = "{0} (rev. {1})".format(name, rev2) else: try: - f1 = open(name, "r", encoding="utf-8") - output2 = f1.read() - f1.close() + with open(name, "r", encoding="utf-8") as f1: + output2 = f1.read() name2 = "{0} (Work)".format(name) except IOError: E5MessageBox.critical( @@ -2140,27 +2139,26 @@ else: createContents = False try: - cfg = open(cfgFile, "w") - if createContents: - # write the data entered - cfg.write("[paths]\n") - if defaultUrl: - cfg.write("default = {0}\n".format(defaultUrl)) - if defaultPushUrl: - cfg.write("default-push = {0}\n".format( - defaultPushUrl)) - if ( - withLargefiles and - (lfMinSize, lfPattern) != (None, None) - ): - cfg.write("\n[largefiles]\n") - if lfMinSize is not None: - cfg.write("minsize = {0}\n".format(lfMinSize)) - if lfPattern is not None: - cfg.write("patterns =\n") - cfg.write(" {0}\n".format( - "\n ".join(lfPattern))) - cfg.close() + with open(cfgFile, "w") as cfg: + if createContents: + # write the data entered + cfg.write("[paths]\n") + if defaultUrl: + cfg.write("default = {0}\n".format(defaultUrl)) + if defaultPushUrl: + cfg.write("default-push = {0}\n".format( + defaultPushUrl)) + if ( + withLargefiles and + (lfMinSize, lfPattern) != (None, None) + ): + cfg.write("\n[largefiles]\n") + if lfMinSize is not None: + cfg.write("minsize = {0}\n".format(lfMinSize)) + if lfPattern is not None: + cfg.write("patterns =\n") + cfg.write(" {0}\n".format( + "\n ".join(lfPattern))) self.__monitorRepoIniFile(repodir) self.__iniFileChanged(cfgFile) except IOError: @@ -2325,10 +2323,9 @@ if res: try: # create a .hgignore file - ignore = open(ignoreName, "w") - ignore.write("\n".join(ignorePatterns)) - ignore.write("\n") - ignore.close() + with open(ignoreName, "w") as ignore: + ignore.write("\n".join(ignorePatterns)) + ignore.write("\n") status = True except IOError: status = False @@ -3062,9 +3059,8 @@ # file exists; check, if such an entry exists already needsAdd = False try: - f = open(hgsub, "r") - contents = f.readlines() - f.close() + with open(hgsub, "r") as f: + contents = f.readlines() except IOError as err: E5MessageBox.critical( self.__ui, @@ -3091,9 +3087,8 @@ contents[-1] = contents[-1] + "\n" contents.append(entry) try: - f = open(hgsub, "w") - f.writelines(contents) - f.close() + with open(hgsub, "w") as f: + f.writelines(contents) except IOError as err: E5MessageBox.critical( self.__ui, @@ -3124,9 +3119,8 @@ return try: - f = open(hgsub, "r") - subrepositories = [line.strip() for line in f.readlines()] - f.close() + with open(hgsub, "r") as f: + subrepositories = [line.strip() for line in f.readlines()] except IOError as err: E5MessageBox.critical( self.__ui, @@ -3144,9 +3138,8 @@ subrepositories, removedSubrepos, deleteSubrepos = dlg.getData() contents = "\n".join(subrepositories) + "\n" try: - f = open(hgsub, "w") - f.write(contents) - f.close() + with open(hgsub, "w") as f: + f.write(contents) except IOError as err: E5MessageBox.critical( self.__ui,
--- a/eric6/Plugins/VcsPlugins/vcsPySvn/SvnDiffDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsPySvn/SvnDiffDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -433,9 +433,8 @@ eol = e5App().getObject("Project").getEolString() try: - f = open(fname, "w", encoding="utf-8", newline="") - f.write(eol.join(self.contents.toPlainText().splitlines())) - f.close() + with open(fname, "w", encoding="utf-8", newline="") as f: + f.write(eol.join(self.contents.toPlainText().splitlines())) except IOError as why: E5MessageBox.critical( self, self.tr('Save Diff'),
--- a/eric6/Plugins/VcsPlugins/vcsPySvn/SvnUtilities.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsPySvn/SvnUtilities.py Wed Oct 14 17:50:39 2020 +0200 @@ -78,9 +78,8 @@ except OSError: pass try: - f = open(config, "w") - f.write(DefaultConfig) - f.close() + with open(config, "w") as f: + f.write(DefaultConfig) except IOError: pass @@ -91,9 +90,8 @@ """ config = getConfigPath() try: - f = open(config, "r") - configList = f.read().splitlines() - f.close() + with open(config, "r") as f: + configList = f.read().splitlines() except IOError: return @@ -129,8 +127,7 @@ if newConfig != configList: try: - f = open(config, "w") - f.write("\n".join(newConfig)) - f.close() + with open(config, "w") as f: + f.write("\n".join(newConfig)) except IOError: pass
--- a/eric6/Plugins/VcsPlugins/vcsPySvn/subversion.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsPySvn/subversion.py Wed Oct 14 17:50:39 2020 +0200 @@ -2196,9 +2196,8 @@ name2 = "{0} (rev. {1})".format(name, rev2) else: try: - f1 = open(name, "r", encoding="utf-8") - output2 = f1.read() - f1.close() + with open(name, "r", encoding="utf-8") as f1: + output2 = f1.read() name2 = name except IOError: E5MessageBox.critical(
--- a/eric6/Plugins/VcsPlugins/vcsSubversion/SvnDiffDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsSubversion/SvnDiffDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -393,9 +393,8 @@ eol = e5App().getObject("Project").getEolString() try: - f = open(fname, "w", encoding="utf-8", newline="") - f.write(eol.join(self.contents.toPlainText().splitlines())) - f.close() + with open(fname, "w", encoding="utf-8", newline="") as f: + f.write(eol.join(self.contents.toPlainText().splitlines())) except IOError as why: E5MessageBox.critical( self, self.tr('Save Diff'),
--- a/eric6/Plugins/VcsPlugins/vcsSubversion/SvnUtilities.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsSubversion/SvnUtilities.py Wed Oct 14 17:50:39 2020 +0200 @@ -52,9 +52,8 @@ except OSError: pass try: - f = open(config, "w") - f.write(DefaultConfig) - f.close() + with open(config, "w") as f: + f.write(DefaultConfig) except IOError: pass @@ -65,9 +64,8 @@ """ config = getConfigPath() try: - f = open(config, "r") - configList = f.read().splitlines() - f.close() + with open(config, "r") as f: + configList = f.read().splitlines() except IOError: return @@ -103,8 +101,7 @@ if newConfig != configList: try: - f = open(config, "w") - f.write("\n".join(newConfig)) - f.close() + with open(config, "w") as f: + f.write("\n".join(newConfig)) except IOError: pass
--- a/eric6/Plugins/VcsPlugins/vcsSubversion/subversion.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsSubversion/subversion.py Wed Oct 14 17:50:39 2020 +0200 @@ -2048,9 +2048,8 @@ name2 = "{0} (rev. {1})".format(name, rev2) else: try: - f1 = open(name, "r", encoding="utf-8") - output2 = f1.read() - f1.close() + with open(name, "r", encoding="utf-8") as f1: + output2 = f1.read() name2 = name except IOError: E5MessageBox.critical(
--- a/eric6/Plugins/WizardPlugins/PyRegExpWizard/PyRegExpWizardDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/WizardPlugins/PyRegExpWizard/PyRegExpWizardDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -340,11 +340,10 @@ if not res: return + fname = Utilities.toNativeSeparators(fname) try: - f = open( - Utilities.toNativeSeparators(fname), "w", encoding="utf-8") - f.write(self.regexpTextEdit.toPlainText()) - f.close() + with open(fname, "w", encoding="utf-8") as f: + f.write(self.regexpTextEdit.toPlainText()) except IOError as err: E5MessageBox.information( self, @@ -364,11 +363,10 @@ "", self.tr("RegExp Files (*.rx);;All Files (*)")) if fname: + fname = Utilities.toNativeSeparators(fname) try: - f = open( - Utilities.toNativeSeparators(fname), "r", encoding="utf-8") - regexp = f.read() - f.close() + with open(fname, "r", encoding="utf-8") as f: + regexp = f.read() self.regexpTextEdit.setPlainText(regexp) except IOError as err: E5MessageBox.information(
--- a/eric6/Plugins/WizardPlugins/QRegularExpressionWizard/QRegularExpressionWizardDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/WizardPlugins/QRegularExpressionWizard/QRegularExpressionWizardDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -422,11 +422,10 @@ if not res: return + fname = Utilities.toNativeSeparators(fname) try: - f = open( - Utilities.toNativeSeparators(fname), "w", encoding="utf-8") - f.write(self.regexpTextEdit.toPlainText()) - f.close() + with open(fname, "w", encoding="utf-8") as f: + f.write(self.regexpTextEdit.toPlainText()) except IOError as err: E5MessageBox.information( self, @@ -446,11 +445,10 @@ "", self.tr("RegExp Files (*.rx);;All Files (*)")) if fname: + fname = Utilities.toNativeSeparators(fname) try: - f = open( - Utilities.toNativeSeparators(fname), "r", encoding="utf-8") - regexp = f.read() - f.close() + with open(fname, "r", encoding="utf-8") as f: + regexp = f.read() self.regexpTextEdit.setPlainText(regexp) except IOError as err: E5MessageBox.information(
--- a/eric6/Plugins/WizardPlugins/SetupWizard/SetupWizardDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Plugins/WizardPlugins/SetupWizard/SetupWizardDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -147,9 +147,8 @@ filename = os.path.join(os.path.dirname(__file__), "data", "trove_classifiers.txt") try: - f = open(filename, "r") - lines = f.readlines() - f.close() + with open(filename, "r") as f: + lines = f.readlines() except (IOError, OSError) as err: E5MessageBox.warning( self,
--- a/eric6/Project/CreateDialogCodeDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Project/CreateDialogCodeDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -421,9 +421,8 @@ """ project type "{0}".</p>""") .format(self.project.getProjectType())) return - tmplFile = open(tmplName, 'r', encoding="utf-8") - template = tmplFile.read() - tmplFile.close() + with open(tmplName, 'r', encoding="utf-8") as tmplFile: + template = tmplFile.read() except IOError as why: E5MessageBox.critical( self, @@ -457,9 +456,8 @@ else: # extend existing file try: - srcFile = open(self.srcFile, 'r', encoding="utf-8") - sourceImpl = srcFile.readlines() - srcFile.close() + with open(self.srcFile, 'r', encoding="utf-8") as srcFile: + sourceImpl = srcFile.readlines() if not sourceImpl[-1].endswith("\n"): sourceImpl[-1] = "{0}{1}".format(sourceImpl[-1], "\n") except IOError as why: @@ -547,25 +545,24 @@ sourceImpl[appendAtIndex:appendAtIndex] = slotsCode # write the new code + if self.project.useSystemEol(): + newline = None + else: + newline = self.project.getEolString() + fn = self.filenameEdit.text() try: - if self.project.useSystemEol(): - newline = None - else: - newline = self.project.getEolString() - srcFile = open(self.filenameEdit.text(), 'w', encoding="utf-8", - newline=newline) - srcFile.write("".join(sourceImpl)) - srcFile.close() + with open(fn, 'w', encoding="utf-8", newline=newline) as srcFile: + srcFile.write("".join(sourceImpl)) except IOError as why: E5MessageBox.critical( self, self.tr("Code Generation"), self.tr("""<p>Could not write the source file "{0}".</p>""" """<p>Reason: {1}</p>""") - .format(self.filenameEdit.text(), str(why))) + .format(fn, str(why))) return - self.project.appendFile(self.filenameEdit.text()) + self.project.appendFile(fn) @pyqtSlot(int) def on_classNameCombo_activated(self, index):
--- a/eric6/Project/Project.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Project/Project.py Wed Oct 14 17:50:39 2020 +0200 @@ -2351,8 +2351,8 @@ "Python3", "MicroPython" ]: fn = os.path.join(self.ppath, "__init__.py") - f = open(fn, "w", encoding="utf-8") - f.close() + with open(fn, "w", encoding="utf-8"): + pass self.appendFile(fn, True) # create an empty main script file, if a name was given @@ -2362,8 +2362,8 @@ self.ppath, self.pdata["MAINSCRIPT"]) else: ms = self.pdata["MAINSCRIPT"] - f = open(ms, "w") - f.close() + with open(ms, "w"): + pass self.appendFile(ms, True) if self.pdata["MAKEPARAMS"]["MakeEnabled"]: @@ -2373,8 +2373,8 @@ mf = os.path.join(self.ppath, mf) else: mf = os.path.join(self.ppath, Project.DefaultMakefile) - f = open(mf, "w") - f.close() + with open(mf, "w"): + pass self.appendFile(mf) tpd = os.path.join(self.ppath, self.translationsRoot) @@ -2415,8 +2415,8 @@ ms = self.pdata["MAINSCRIPT"] if not os.path.exists(ms): try: - f = open(ms, "w") - f.close() + with open(ms, "w"): + pass except EnvironmentError as err: E5MessageBox.critical( self.ui, @@ -2438,8 +2438,8 @@ mf = os.path.join(self.ppath, Project.DefaultMakefile) if not os.path.exists(mf): try: - f = open(mf, "w") - f.close() + with open(mf, "w"): + pass except EnvironmentError as err: E5MessageBox.critical( self.ui, @@ -2466,8 +2466,8 @@ ]: fn = os.path.join(self.ppath, "__init__.py") if not os.path.exists(fn): - f = open(fn, "w", encoding="utf-8") - f.close() + with open(fn, "w", encoding="utf-8"): + pass self.appendFile(fn, True) self.saveProject() @@ -2729,8 +2729,8 @@ mf = os.path.join(self.ppath, Project.DefaultMakefile) if not os.path.exists(mf): try: - f = open(mf, "w") - f.close() + with open(mf, "w"): + pass except EnvironmentError as err: E5MessageBox.critical( self.ui, @@ -5269,12 +5269,14 @@ newline = None else: newline = self.getEolString() - pkglistFile = open(pkglist, "w", encoding="utf-8", newline=newline) - pkglistFile.write("\n".join(header) + "\n") - pkglistFile.write( - "\n".join([Utilities.fromNativeSeparators(f) for f in lst])) - pkglistFile.write("\n") # ensure the file ends with an empty line - pkglistFile.close() + with open(pkglist, "w", encoding="utf-8", + newline=newline) as pkglistFile: + pkglistFile.write("\n".join(header) + "\n") + pkglistFile.write( + "\n".join([Utilities.fromNativeSeparators(f) + for f in lst])) + pkglistFile.write("\n") + # ensure the file ends with an empty line except IOError as why: E5MessageBox.critical( self.ui, @@ -5340,9 +5342,8 @@ break try: - pkglistFile = open(pkglist, "r", encoding="utf-8") - names = pkglistFile.read() - pkglistFile.close() + with open(pkglist, "r", encoding="utf-8") as pkglistFile: + names = pkglistFile.read() except IOError as why: E5MessageBox.critical( self.ui,
--- a/eric6/Project/ProjectFormsBrowser.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Project/ProjectFormsBrowser.py Wed Oct 14 17:50:39 2020 +0200 @@ -748,10 +748,9 @@ newline = None else: newline = self.project.getEolString() - f = open(ofn, "w", encoding="utf-8", newline=newline) - for line in self.buf.splitlines(): - f.write(line + "\n") - f.close() + with open(ofn, "w", encoding="utf-8", newline=newline) as f: + for line in self.buf.splitlines(): + f.write(line + "\n") if self.compiledFile not in self.project.pdata["SOURCES"]: self.project.appendFile(ofn) if not self.noDialog and not ui.notificationsEnabled():
--- a/eric6/Project/ProjectResourcesBrowser.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Project/ProjectResourcesBrowser.py Wed Oct 14 17:50:39 2020 +0200 @@ -492,13 +492,13 @@ newline = None else: newline = self.project.getEolString() - rcfile = open(fname, 'w', encoding="utf-8", newline=newline) - rcfile.write('<!DOCTYPE RCC>\n') - rcfile.write('<RCC version="1.0">\n') - rcfile.write('<qresource>\n') - rcfile.write('</qresource>\n') - rcfile.write('</RCC>\n') - rcfile.close() + with open(fname, 'w', encoding="utf-8", + newline=newline) as rcfile: + rcfile.write('<!DOCTYPE RCC>\n') + rcfile.write('<RCC version="1.0">\n') + rcfile.write('<qresource>\n') + rcfile.write('</qresource>\n') + rcfile.write('</RCC>\n') except IOError as e: E5MessageBox.critical( self, @@ -595,10 +595,9 @@ newline = None else: newline = self.project.getEolString() - f = open(ofn, "w", encoding="utf-8", newline=newline) - for line in self.buf.splitlines(): - f.write(line + "\n") - f.close() + with open(ofn, "w", encoding="utf-8", newline=newline) as f: + for line in self.buf.splitlines(): + f.write(line + "\n") if self.compiledFile not in self.project.pdata["SOURCES"]: self.project.appendFile(ofn) if not self.noDialog and not ui.notificationsEnabled(): @@ -815,9 +814,8 @@ @return flag indicating some file is newer (boolean) """ try: - f = open(filename, "r", encoding="utf-8") - buf = f.read() - f.close() + with open(filename, "r", encoding="utf-8") as f: + buf = f.read() except IOError: return False
--- a/eric6/Project/ProjectSourcesBrowser.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Project/ProjectSourcesBrowser.py Wed Oct 14 17:50:39 2020 +0200 @@ -837,8 +837,8 @@ packageFile = os.path.join(packagePath, "__init__.py") if not os.path.exists(packageFile): try: - f = open(packageFile, "w", encoding="utf-8") - f.close() + with open(packageFile, "w", encoding="utf-8"): + pass except IOError as err: E5MessageBox.critical( self,
--- a/eric6/Project/ProjectTranslationsBrowser.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Project/ProjectTranslationsBrowser.py Wed Oct 14 17:50:39 2020 +0200 @@ -809,15 +809,14 @@ if not os.path.exists(outDir): os.makedirs(outDir) try: - pf = open(outFile, "w", encoding="utf-8") - for key, fileList in sections: - if len(fileList) > 0: - pf.write('{0} = '.format(key)) - pf.write(' \\\n\t'.join( - [f.replace(os.sep, '/') for f in fileList])) - pf.write('\n\n') + with open(outFile, "w", encoding="utf-8") as pf: + for key, fileList in sections: + if len(fileList) > 0: + pf.write('{0} = '.format(key)) + pf.write(' \\\n\t'.join( + [f.replace(os.sep, '/') for f in fileList])) + pf.write('\n\n') - pf.close() self.__tmpProjects.append(outFile) except IOError: E5MessageBox.critical(
--- a/eric6/QScintilla/Editor.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/QScintilla/Editor.py Wed Oct 14 17:50:39 2020 +0200 @@ -3083,8 +3083,8 @@ try: with E5OverrideCursor(): if createIt and not os.path.exists(fn): - f = open(fn, "w") - f.close() + with open(fn, "w"): + pass if encoding == "": encoding = self.__getEditorConfig("DefaultEncoding", nodefault=True) @@ -6742,9 +6742,8 @@ return # user aborted try: - f = open(fname, "r", encoding="utf-8") - lines = f.readlines() - f.close() + with open(fname, "r", encoding="utf-8") as f: + lines = f.readlines() except IOError: E5MessageBox.critical( self, @@ -6803,10 +6802,9 @@ fname = Utilities.toNativeSeparators(fname) try: - f = open(fname, "w", encoding="utf-8") - f.write("{0}{1}".format(name, "\n")) - f.write(self.macros[name].save()) - f.close() + with open(fname, "w", encoding="utf-8") as f: + f.write("{0}{1}".format(name, "\n")) + f.write(self.macros[name].save()) except IOError: E5MessageBox.critical( self,
--- a/eric6/QScintilla/Exporters/ExporterHTML.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/QScintilla/Exporters/ExporterHTML.py Wed Oct 14 17:50:39 2020 +0200 @@ -454,9 +454,8 @@ if html: try: with E5OverrideCursor(): - f = open(filename, "w", encoding="utf-8") - f.write(html) - f.close() + with open(filename, "w", encoding="utf-8") as f: + f.write(html) except IOError as err: E5MessageBox.critical( self.editor,
--- a/eric6/QScintilla/Exporters/ExporterPDF.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/QScintilla/Exporters/ExporterPDF.py Wed Oct 14 17:50:39 2020 +0200 @@ -543,74 +543,73 @@ try: with E5OverrideCursor(): # save file in win ansi using cp1250 - f = open(filename, "w", encoding="cp1250", - errors="backslashreplace") - - # initialise PDF rendering - ot = PDFObjectTracker(f) - self.pr.oT = ot - self.pr.startPDF() - - # do here all the writing - lengthDoc = self.editor.length() - - if lengthDoc == 0: - self.pr.nextLine() # enable zero length docs - else: - pos = 0 - column = 0 - utf8 = self.editor.isUtf8() - utf8Ch = b"" - utf8Len = 0 + with open(filename, "w", encoding="cp1250", + errors="backslashreplace") as f: + + # initialise PDF rendering + ot = PDFObjectTracker(f) + self.pr.oT = ot + self.pr.startPDF() - while pos < lengthDoc: - ch = self.editor.byteAt(pos) - style = self.editor.styleAt(pos) + # do here all the writing + lengthDoc = self.editor.length() + + if lengthDoc == 0: + self.pr.nextLine() # enable zero length docs + else: + pos = 0 + column = 0 + utf8 = self.editor.isUtf8() + utf8Ch = b"" + utf8Len = 0 - if ch == b'\t': - # expand tabs - ts = tabSize - (column % tabSize) - column += ts - self.pr.add(' ' * ts, style) - elif ch == b'\r' or ch == b'\n': - if ( - ch == b'\r' and - self.editor.byteAt(pos + 1) == b'\n' - ): - pos += 1 - # close and begin a newline... - self.pr.nextLine() - column = 0 - else: - # write the character normally... - if ord(ch) > 127 and utf8: - utf8Ch += ch - if utf8Len == 0: - if (utf8Ch[0] & 0xF0) == 0xF0: - utf8Len = 4 - elif (utf8Ch[0] & 0xE0) == 0xE0: - utf8Len = 3 - elif (utf8Ch[0] & 0xC0) == 0xC0: - utf8Len = 2 - column -= 1 - # will be incremented again later - elif len(utf8Ch) == utf8Len: - ch = utf8Ch.decode('utf8') - self.pr.add(ch, style) - utf8Ch = b"" - utf8Len = 0 + while pos < lengthDoc: + ch = self.editor.byteAt(pos) + style = self.editor.styleAt(pos) + + if ch == b'\t': + # expand tabs + ts = tabSize - (column % tabSize) + column += ts + self.pr.add(' ' * ts, style) + elif ch == b'\r' or ch == b'\n': + if ( + ch == b'\r' and + self.editor.byteAt(pos + 1) == b'\n' + ): + pos += 1 + # close and begin a newline... + self.pr.nextLine() + column = 0 + else: + # write the character normally... + if ord(ch) > 127 and utf8: + utf8Ch += ch + if utf8Len == 0: + if (utf8Ch[0] & 0xF0) == 0xF0: + utf8Len = 4 + elif (utf8Ch[0] & 0xE0) == 0xE0: + utf8Len = 3 + elif (utf8Ch[0] & 0xC0) == 0xC0: + utf8Len = 2 + column -= 1 + # will be incremented again later + elif len(utf8Ch) == utf8Len: + ch = utf8Ch.decode('utf8') + self.pr.add(ch, style) + utf8Ch = b"" + utf8Len = 0 + else: + column -= 1 + # will be incremented again later else: - column -= 1 - # will be incremented again later - else: - self.pr.add(ch.decode(), style) - column += 1 - - pos += 1 - - # write required stuff and close the PDF file - self.pr.endPDF() - f.close() + self.pr.add(ch.decode(), style) + column += 1 + + pos += 1 + + # write required stuff and close the PDF file + self.pr.endPDF() except IOError as err: E5MessageBox.critical( self.editor,
--- a/eric6/QScintilla/Exporters/ExporterRTF.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/QScintilla/Exporters/ExporterRTF.py Wed Oct 14 17:50:39 2020 +0200 @@ -149,218 +149,222 @@ try: with E5OverrideCursor(): - f = open(filename, "w", encoding="utf-8") - - styles = {} - fonts = {} - colors = {} - lastStyle = "" - - f.write(self.RTF_HEADEROPEN + self.RTF_FONTDEFOPEN) - fonts[0] = fontface - fontCount = 1 - f.write(self.RTF_FONTDEF.format(0, characterset, fontface)) - colors[0] = fgColour - colors[1] = bgColour - colorCount = 2 - - if lex: - istyle = 0 - while istyle <= QsciScintilla.STYLE_MAX: - if (istyle < QsciScintilla.STYLE_DEFAULT or - istyle > QsciScintilla.STYLE_LASTPREDEFINED): - if lex.description(istyle): - font = lex.font(istyle) - if wysiwyg: - fontKey = None - for key, value in list(fonts.items()): - if ( - value.lower() == - font.family().lower() - ): - fontKey = key + with open(filename, "w", encoding="utf-8") as f: + + styles = {} + fonts = {} + colors = {} + lastStyle = "" + + f.write(self.RTF_HEADEROPEN + self.RTF_FONTDEFOPEN) + fonts[0] = fontface + fontCount = 1 + f.write(self.RTF_FONTDEF.format(0, characterset, fontface)) + colors[0] = fgColour + colors[1] = bgColour + colorCount = 2 + + if lex: + istyle = 0 + while istyle <= QsciScintilla.STYLE_MAX: + if ( + istyle < QsciScintilla.STYLE_DEFAULT or + istyle > QsciScintilla.STYLE_LASTPREDEFINED + ): + if lex.description(istyle): + font = lex.font(istyle) + if wysiwyg: + fontKey = None + for key, value in list(fonts.items()): + if ( + value.lower() == + font.family().lower() + ): + fontKey = key + break + if fontKey is None: + fonts[fontCount] = font.family() + f.write(self.RTF_FONTDEF.format( + fontCount, characterset, + font.family())) + fontKey = fontCount + fontCount += 1 + lastStyle = ( + self.RTF_SETFONTFACE + + "{0:d}".format(fontKey) + ) + else: + lastStyle = self.RTF_SETFONTFACE + "0" + + if wysiwyg and QFontInfo(font).pointSize(): + lastStyle += ( + self.RTF_SETFONTSIZE + + "{0:d}".format( + QFontInfo(font).pointSize() << + 1) + ) + else: + lastStyle += ( + self.RTF_SETFONTSIZE + + "{0:d}".format(fontsize) + ) + + sColour = lex.color(istyle) + sColourKey = None + for key, value in list(colors.items()): + if value == sColour: + sColourKey = key break - if fontKey is None: - fonts[fontCount] = font.family() - f.write(self.RTF_FONTDEF.format( - fontCount, characterset, - font.family())) - fontKey = fontCount - fontCount += 1 - lastStyle = ( - self.RTF_SETFONTFACE + - "{0:d}".format(fontKey) - ) - else: - lastStyle = self.RTF_SETFONTFACE + "0" - - if wysiwyg and QFontInfo(font).pointSize(): + if sColourKey is None: + colors[colorCount] = sColour + sColourKey = colorCount + colorCount += 1 lastStyle += ( - self.RTF_SETFONTSIZE + - "{0:d}".format( - QFontInfo(font).pointSize() << 1) - ) - else: - lastStyle += ( - self.RTF_SETFONTSIZE + - "{0:d}".format(fontsize) + self.RTF_SETCOLOR + + "{0:d}".format(sColourKey) ) - - sColour = lex.color(istyle) - sColourKey = None - for key, value in list(colors.items()): - if value == sColour: - sColourKey = key - break - if sColourKey is None: - colors[colorCount] = sColour - sColourKey = colorCount - colorCount += 1 - lastStyle += ( - self.RTF_SETCOLOR + - "{0:d}".format(sColourKey) - ) - - sColour = lex.paper(istyle) - sColourKey = None - for key, value in list(colors.items()): - if value == sColour: - sColourKey = key - break - if sColourKey is None: - colors[colorCount] = sColour - sColourKey = colorCount - colorCount += 1 - lastStyle += ( - self.RTF_SETBACKGROUND + - "{0:d}".format(sColourKey) - ) - - if font.bold(): - lastStyle += self.RTF_BOLD_ON + + sColour = lex.paper(istyle) + sColourKey = None + for key, value in list(colors.items()): + if value == sColour: + sColourKey = key + break + if sColourKey is None: + colors[colorCount] = sColour + sColourKey = colorCount + colorCount += 1 + lastStyle += ( + self.RTF_SETBACKGROUND + + "{0:d}".format(sColourKey) + ) + + if font.bold(): + lastStyle += self.RTF_BOLD_ON + else: + lastStyle += self.RTF_BOLD_OFF + if font.italic(): + lastStyle += self.RTF_ITALIC_ON + else: + lastStyle += self.RTF_ITALIC_OFF + styles[istyle] = lastStyle else: - lastStyle += self.RTF_BOLD_OFF - if font.italic(): - lastStyle += self.RTF_ITALIC_ON - else: - lastStyle += self.RTF_ITALIC_OFF - styles[istyle] = lastStyle - else: - styles[istyle] = ( - self.RTF_SETFONTFACE + "0" + - self.RTF_SETFONTSIZE + - "{0:d}".format(fontsize) + - self.RTF_SETCOLOR + "0" + - self.RTF_SETBACKGROUND + "1" + - self.RTF_BOLD_OFF + - self.RTF_ITALIC_OFF - ) - - istyle += 1 - else: - styles[0] = ( + styles[istyle] = ( + self.RTF_SETFONTFACE + "0" + + self.RTF_SETFONTSIZE + + "{0:d}".format(fontsize) + + self.RTF_SETCOLOR + "0" + + self.RTF_SETBACKGROUND + "1" + + self.RTF_BOLD_OFF + + self.RTF_ITALIC_OFF + ) + + istyle += 1 + else: + styles[0] = ( + self.RTF_SETFONTFACE + "0" + + self.RTF_SETFONTSIZE + + "{0:d}".format(fontsize) + + self.RTF_SETCOLOR + "0" + + self.RTF_SETBACKGROUND + "1" + + self.RTF_BOLD_OFF + + self.RTF_ITALIC_OFF + ) + + f.write(self.RTF_FONTDEFCLOSE + self.RTF_COLORDEFOPEN) + for value in list(colors.values()): + f.write(self.RTF_COLORDEF.format( + value.red(), value.green(), value.blue())) + f.write(self.RTF_COLORDEFCLOSE) + f.write(self.RTF_INFOOPEN + self.RTF_COMMENT) + f.write(time.strftime(self.RTF_CREATED)) + f.write(self.RTF_INFOCLOSE) + f.write(self.RTF_HEADERCLOSE + + self.RTF_BODYOPEN + self.RTF_SETFONTFACE + "0" + + self.RTF_SETFONTSIZE + "{0:d}".format(fontsize) + + self.RTF_SETCOLOR + "0 ") + lastStyle = ( self.RTF_SETFONTFACE + "0" + - self.RTF_SETFONTSIZE + - "{0:d}".format(fontsize) + + self.RTF_SETFONTSIZE + "{0:d}".format(fontsize) + self.RTF_SETCOLOR + "0" + self.RTF_SETBACKGROUND + "1" + self.RTF_BOLD_OFF + self.RTF_ITALIC_OFF ) - - f.write(self.RTF_FONTDEFCLOSE + self.RTF_COLORDEFOPEN) - for value in list(colors.values()): - f.write(self.RTF_COLORDEF.format( - value.red(), value.green(), value.blue())) - f.write(self.RTF_COLORDEFCLOSE) - f.write(self.RTF_INFOOPEN + self.RTF_COMMENT) - f.write(time.strftime(self.RTF_CREATED)) - f.write(self.RTF_INFOCLOSE) - f.write(self.RTF_HEADERCLOSE + - self.RTF_BODYOPEN + self.RTF_SETFONTFACE + "0" + - self.RTF_SETFONTSIZE + "{0:d}".format(fontsize) + - self.RTF_SETCOLOR + "0 ") - lastStyle = ( - self.RTF_SETFONTFACE + "0" + - self.RTF_SETFONTSIZE + "{0:d}".format(fontsize) + - self.RTF_SETCOLOR + "0" + - self.RTF_SETBACKGROUND + "1" + - self.RTF_BOLD_OFF + - self.RTF_ITALIC_OFF - ) - - lengthDoc = self.editor.length() - prevCR = False - column = 0 - pos = 0 - deltaStyle = "" - styleCurrent = -1 - utf8 = self.editor.isUtf8() - utf8Ch = b"" - utf8Len = 0 - - while pos < lengthDoc: - ch = self.editor.byteAt(pos) - style = self.editor.styleAt(pos) - if style != styleCurrent: - deltaStyle = self.__GetRTFStyleChange( - lastStyle, styles[style]) - if deltaStyle: - f.write(deltaStyle) - styleCurrent = style - lastStyle = styles[style] + + lengthDoc = self.editor.length() + prevCR = False + column = 0 + pos = 0 + deltaStyle = "" + styleCurrent = -1 + utf8 = self.editor.isUtf8() + utf8Ch = b"" + utf8Len = 0 - if ch == b'{': - f.write('\\{') - elif ch == b'}': - f.write('\\}') - elif ch == b'\\': - f.write('\\\\') - elif ch == b'\t': - if tabs: - f.write(self.RTF_TAB) - else: - ts = tabSize - (column % tabSize) - f.write(' ' * ts) - column += ts - 1 - elif ch == b'\n': - if not prevCR: + while pos < lengthDoc: + ch = self.editor.byteAt(pos) + style = self.editor.styleAt(pos) + if style != styleCurrent: + deltaStyle = self.__GetRTFStyleChange( + lastStyle, styles[style]) + if deltaStyle: + f.write(deltaStyle) + styleCurrent = style + lastStyle = styles[style] + + if ch == b'{': + f.write('\\{') + elif ch == b'}': + f.write('\\}') + elif ch == b'\\': + f.write('\\\\') + elif ch == b'\t': + if tabs: + f.write(self.RTF_TAB) + else: + ts = tabSize - (column % tabSize) + f.write(' ' * ts) + column += ts - 1 + elif ch == b'\n': + if not prevCR: + f.write(self.RTF_EOLN) + column -= 1 + elif ch == b'\r': f.write(self.RTF_EOLN) column -= 1 - elif ch == b'\r': - f.write(self.RTF_EOLN) - column -= 1 - else: - if ord(ch) > 0x7F and utf8: - utf8Ch += ch - if utf8Len == 0: - if (utf8Ch[0] & 0xF0) == 0xF0: - utf8Len = 4 - elif (utf8Ch[0] & 0xE0) == 0xE0: - utf8Len = 3 - elif (utf8Ch[0] & 0xC0) == 0xC0: - utf8Len = 2 - column -= 1 # will be incremented again later - elif len(utf8Ch) == utf8Len: - ch = utf8Ch.decode('utf8') - if ord(ch) <= 0xff: - f.write("\\'{0:x}".format(ord(ch))) + else: + if ord(ch) > 0x7F and utf8: + utf8Ch += ch + if utf8Len == 0: + if (utf8Ch[0] & 0xF0) == 0xF0: + utf8Len = 4 + elif (utf8Ch[0] & 0xE0) == 0xE0: + utf8Len = 3 + elif (utf8Ch[0] & 0xC0) == 0xC0: + utf8Len = 2 + column -= 1 + # will be incremented again later + elif len(utf8Ch) == utf8Len: + ch = utf8Ch.decode('utf8') + if ord(ch) <= 0xff: + f.write("\\'{0:x}".format(ord(ch))) + else: + f.write("\\u{0:d}\\'{1:x}".format( + ord(ch), ord(ch) & 0xFF)) + utf8Ch = b"" + utf8Len = 0 else: - f.write("\\u{0:d}\\'{1:x}".format( - ord(ch), ord(ch) & 0xFF)) - utf8Ch = b"" - utf8Len = 0 + column -= 1 + # will be incremented again later else: - column -= 1 # will be incremented again later - else: - f.write(ch.decode()) + f.write(ch.decode()) + + column += 1 + prevCR = ch == b'\r' + pos += 1 - column += 1 - prevCR = ch == b'\r' - pos += 1 - - f.write(self.RTF_BODYCLOSE) - f.close() + f.write(self.RTF_BODYCLOSE) except IOError as err: E5MessageBox.critical( self.editor,
--- a/eric6/QScintilla/Exporters/ExporterTEX.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/QScintilla/Exporters/ExporterTEX.py Wed Oct 14 17:50:39 2020 +0200 @@ -157,122 +157,124 @@ try: with E5OverrideCursor(): - f = open(filename, "w", encoding="utf-8") - - f.write("\\documentclass[a4paper]{article}\n") - f.write("\\usepackage[a4paper,margin=1.5cm]{geometry}\n") - f.write("\\usepackage[T1]{fontenc}\n") - f.write("\\usepackage{color}\n") - f.write("\\usepackage{alltt}\n") - f.write("\\usepackage{times}\n") - if self.editor.isUtf8(): - f.write("\\usepackage[utf8]{inputenc}\n") - else: - f.write("\\usepackage[latin1]{inputenc}\n") - - if lex: - istyle = 0 - while istyle <= QsciScintilla.STYLE_MAX: - if ( - (istyle <= QsciScintilla.STYLE_DEFAULT or - istyle > QsciScintilla.STYLE_LASTPREDEFINED) and - styleIsUsed[istyle] - ): + with open(filename, "w", encoding="utf-8") as f: + + f.write("\\documentclass[a4paper]{article}\n") + f.write("\\usepackage[a4paper,margin=1.5cm]{geometry}\n") + f.write("\\usepackage[T1]{fontenc}\n") + f.write("\\usepackage{color}\n") + f.write("\\usepackage{alltt}\n") + f.write("\\usepackage{times}\n") + if self.editor.isUtf8(): + f.write("\\usepackage[utf8]{inputenc}\n") + else: + f.write("\\usepackage[latin1]{inputenc}\n") + + if lex: + istyle = 0 + while istyle <= QsciScintilla.STYLE_MAX: if ( - lex.description(istyle) or - istyle == QsciScintilla.STYLE_DEFAULT + (istyle <= QsciScintilla.STYLE_DEFAULT or + istyle > QsciScintilla.STYLE_LASTPREDEFINED + ) and styleIsUsed[istyle] ): - font = lex.font(istyle) - colour = lex.color(istyle) - paper = lex.paper(istyle) - - self.__defineTexStyle(font, colour, paper, f, - istyle) - istyle += 1 - else: - colour = self.editor.color() - paper = self.editor.paper() - font = Preferences.getEditorOtherFonts("DefaultFont") + if ( + lex.description(istyle) or + istyle == QsciScintilla.STYLE_DEFAULT + ): + font = lex.font(istyle) + colour = lex.color(istyle) + paper = lex.paper(istyle) + + self.__defineTexStyle( + font, colour, paper, f, istyle) + istyle += 1 + else: + colour = self.editor.color() + paper = self.editor.paper() + font = Preferences.getEditorOtherFonts("DefaultFont") + + self.__defineTexStyle(font, colour, paper, f, 0) + self.__defineTexStyle(font, colour, paper, f, + QsciScintilla.STYLE_DEFAULT) + + f.write("\\begin{document}\n\n") + if titleFullPath: + title = self.editor.getFileName() + else: + title = os.path.basename(self.editor.getFileName()) + f.write( + "Source File: {0}\n\n\\noindent\n\\tiny{{\n" + .format(title)) + + styleCurrent = self.editor.styleAt(0) + f.write("\\eric{0}{{" + .format(self.__texStyle(styleCurrent))) - self.__defineTexStyle(font, colour, paper, f, 0) - self.__defineTexStyle(font, colour, paper, f, - QsciScintilla.STYLE_DEFAULT) - - f.write("\\begin{document}\n\n") - if titleFullPath: - title = self.editor.getFileName() - else: - title = os.path.basename(self.editor.getFileName()) - f.write( - "Source File: {0}\n\n\\noindent\n\\tiny{{\n".format(title)) - - styleCurrent = self.editor.styleAt(0) - f.write("\\eric{0}{{".format(self.__texStyle(styleCurrent))) - - lineIdx = 0 - pos = 0 - utf8 = self.editor.isUtf8() - utf8Ch = b"" - utf8Len = 0 - - while pos < lengthDoc: - ch = self.editor.byteAt(pos) - style = self.editor.styleAt(pos) - if style != styleCurrent: - # new style - f.write( - "}}\n\\eric{0}{{".format(self.__texStyle(style))) - styleCurrent = style + lineIdx = 0 + pos = 0 + utf8 = self.editor.isUtf8() + utf8Ch = b"" + utf8Len = 0 - if ch == b'\t': - ts = tabSize - (lineIdx % tabSize) - lineIdx += ts - 1 - f.write("\\hspace*{{{0:d}em}}".format(ts)) - elif ch == b'\\': - f.write("{\\textbackslash}") - elif ch in [b'>', b'<', b'@']: - f.write("${0}$".format(ch[0])) - elif ch in [b'{', b'}', b'^', b'_', b'&', b'$', b'#', - b'%', b'~']: - f.write("\\{0}".format(ch[0])) - elif ch in [b'\r', b'\n']: - lineIdx = -1 # because incremented below - if ( - ch == b'\r' and - self.editor.byteAt(pos + 1) == b'\n' - ): - pos += 1 # skip the LF - styleCurrent = self.editor.styleAt(pos + 1) - f.write("}} \\\\\n\\eric{0}{{".format( - self.__texStyle(styleCurrent))) - elif ch == b' ': - if self.editor.byteAt(pos + 1) == b' ': - f.write("{\\hspace*{1em}}") + while pos < lengthDoc: + ch = self.editor.byteAt(pos) + style = self.editor.styleAt(pos) + if style != styleCurrent: + # new style + f.write( + "}}\n\\eric{0}{{".format( + self.__texStyle(style))) + styleCurrent = style + + if ch == b'\t': + ts = tabSize - (lineIdx % tabSize) + lineIdx += ts - 1 + f.write("\\hspace*{{{0:d}em}}".format(ts)) + elif ch == b'\\': + f.write("{\\textbackslash}") + elif ch in [b'>', b'<', b'@']: + f.write("${0}$".format(ch[0])) + elif ch in [b'{', b'}', b'^', b'_', b'&', b'$', b'#', + b'%', b'~']: + f.write("\\{0}".format(ch[0])) + elif ch in [b'\r', b'\n']: + lineIdx = -1 # because incremented below + if ( + ch == b'\r' and + self.editor.byteAt(pos + 1) == b'\n' + ): + pos += 1 # skip the LF + styleCurrent = self.editor.styleAt(pos + 1) + f.write("}} \\\\\n\\eric{0}{{".format( + self.__texStyle(styleCurrent))) + elif ch == b' ': + if self.editor.byteAt(pos + 1) == b' ': + f.write("{\\hspace*{1em}}") + else: + f.write(' ') else: - f.write(' ') - else: - if ord(ch) > 127 and utf8: - utf8Ch += ch - if utf8Len == 0: - if (utf8Ch[0] & 0xF0) == 0xF0: - utf8Len = 4 - elif (utf8Ch[0] & 0xE0) == 0xE0: - utf8Len = 3 - elif (utf8Ch[0] & 0xC0) == 0xC0: - utf8Len = 2 - elif len(utf8Ch) == utf8Len: - ch = utf8Ch.decode('utf8') - f.write(ch) - utf8Ch = b"" - utf8Len = 0 - else: - f.write(ch.decode()) - lineIdx += 1 - pos += 1 - - # close last empty style macros and document too - f.write("}\n} %end tiny\n\n\\end{document}\n") - f.close() + if ord(ch) > 127 and utf8: + utf8Ch += ch + if utf8Len == 0: + if (utf8Ch[0] & 0xF0) == 0xF0: + utf8Len = 4 + elif (utf8Ch[0] & 0xE0) == 0xE0: + utf8Len = 3 + elif (utf8Ch[0] & 0xC0) == 0xC0: + utf8Len = 2 + elif len(utf8Ch) == utf8Len: + ch = utf8Ch.decode('utf8') + f.write(ch) + utf8Ch = b"" + utf8Len = 0 + else: + f.write(ch.decode()) + lineIdx += 1 + pos += 1 + + # close last empty style macros and document too + f.write("}\n} %end tiny\n\n\\end{document}\n") except IOError as err: E5MessageBox.critical( self.editor,
--- a/eric6/UI/CompareDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/UI/CompareDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -237,9 +237,8 @@ """ filename1 = self.file1Picker.text() try: - f1 = open(filename1, "r", encoding="utf-8") - lines1 = f1.readlines() - f1.close() + with open(filename1, "r", encoding="utf-8") as f1: + lines1 = f1.readlines() except IOError: E5MessageBox.critical( self, @@ -251,9 +250,8 @@ filename2 = self.file2Picker.text() try: - f2 = open(filename2, "r", encoding="utf-8") - lines2 = f2.readlines() - f2.close() + with open(filename2, "r", encoding="utf-8") as f2: + lines2 = f2.readlines() except IOError: E5MessageBox.critical( self,
--- a/eric6/UI/DiffDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/UI/DiffDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -133,14 +133,13 @@ return fname = Utilities.toNativeSeparators(fname) + txt = self.contents.toPlainText() try: - f = open(fname, "w", encoding="utf-8") - txt = self.contents.toPlainText() - try: - f.write(txt) - except UnicodeError: - pass - f.close() + with open(fname, "w", encoding="utf-8") as f: + try: + f.write(txt) + except UnicodeError: + pass except IOError as why: E5MessageBox.critical( self, self.tr('Save Diff'), @@ -159,9 +158,8 @@ except IOError: filemtime1 = "" try: - f1 = open(self.filename1, "r", encoding="utf-8") - lines1 = f1.readlines() - f1.close() + with open(self.filename1, "r", encoding="utf-8") as f1: + lines1 = f1.readlines() except IOError: E5MessageBox.critical( self, @@ -177,9 +175,8 @@ except IOError: filemtime2 = "" try: - f2 = open(self.filename2, "r", encoding="utf-8") - lines2 = f2.readlines() - f2.close() + with open(self.filename2, "r", encoding="utf-8") as f2: + lines2 = f2.readlines() except IOError: E5MessageBox.critical( self,
--- a/eric6/UI/EmailDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/UI/EmailDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -276,7 +276,8 @@ name = os.path.basename(fname) if maintype == 'text': - txt = open(fname, 'r', encoding="utf-8").read() + with open(fname, 'r', encoding="utf-8") as f: + txt = f.read() try: txt.encode("us-ascii") att = MIMEText(txt, _subtype=subtype)
--- a/eric6/UI/ErrorLogDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/UI/ErrorLogDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -49,9 +49,8 @@ self.__logFile = logFile try: - f = open(logFile, "r", encoding="utf-8") - txt = f.read() - f.close() + with open(logFile, "r", encoding="utf-8") as f: + txt = f.read() self.logEdit.setPlainText(txt) except IOError: pass
--- a/eric6/UI/Previewers/PreviewerHTML.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/UI/Previewers/PreviewerHTML.py Wed Oct 14 17:50:39 2020 +0200 @@ -497,9 +497,8 @@ incFile = "" if os.path.exists(incFile): try: - f = open(incFile, "r") - incTxt = f.read() - f.close() + with open(incFile, "r") as f: + incTxt = f.read() except (IOError, OSError): # remove SSI include incTxt = "" @@ -585,10 +584,9 @@ try: filename = 'sphinx_preview' basePath = os.path.join(srcTempDir, filename) - fh = open(basePath + '.rst', 'w', encoding='utf-8') - fh.write(text) - fh.close() - + with open(basePath + '.rst', 'w', encoding='utf-8') as fh: + fh.write(text) + overrides = {'html_add_permalinks': False, 'html_copy_source': False, 'html_title': 'Sphinx preview', @@ -603,9 +601,8 @@ app.build(force_all=True, filenames=None) basePath = os.path.join(outTempDir, filename) - fh = open(basePath + '.html', 'r', encoding='utf-8') - html = fh.read() - fh.close() + with open(basePath + '.html', 'r', encoding='utf-8') as fh: + html = fh.read() finally: shutil.rmtree(srcTempDir) shutil.rmtree(outTempDir)
--- a/eric6/UI/UserInterface.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/UI/UserInterface.py Wed Oct 14 17:50:39 2020 +0200 @@ -3692,9 +3692,8 @@ address = BugAddress subject = "[eric6] " if attachFile is not None: - f = open(attachFile, "r", encoding="utf-8") - body = f.read() - f.close() + with open(attachFile, "r", encoding="utf-8") as f: + body = f.read() if deleteAttachFile: os.remove(attachFile) else:
--- a/eric6/Utilities/__init__.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/Utilities/__init__.py Wed Oct 14 17:50:39 2020 +0200 @@ -171,9 +171,8 @@ @param filename name of the file to read (string) @return tuple of decoded text and encoding (string, string) """ - f = open(filename, "rb") - text = f.read() - f.close() + with open(filename, "rb") as f: + text = f.read() return decode(text) @@ -186,9 +185,8 @@ @return tuple of decoded text, encoding and hash value (string, string, string) """ - f = open(filename, "rb") - text = f.read() - f.close() + with open(filename, "rb") as f: + text = f.read() hashStr = str(QCryptographicHash.hash( QByteArray(text), QCryptographicHash.Md5).toHex(), encoding="ASCII") return decode(text) + (hashStr, ) @@ -269,9 +267,8 @@ @keyparam encoding encoding to be used to read the file (string) @return tuple of decoded text and encoding (string, string) """ - f = open(filename, "rb") - text = f.read() - f.close() + with open(filename, "rb") as f: + text = f.read() if encoding: try: return str(text, encoding), '{0}-selected'.format(encoding) @@ -307,9 +304,8 @@ """ etext, encoding = encode(text, origEncoding, forcedEncoding=forcedEncoding) - f = open(filename, "wb") - f.write(etext) - f.close() + with open(filename, "wb") as f: + f.write(etext) return encoding @@ -2041,9 +2037,8 @@ info.append("Distribution Info:") for rfile in releaseList: try: - f = open(rfile, "r") - lines = f.read().splitlines() - f.close + with open(rfile, "r") as f: + lines = f.read().splitlines() except IOError: continue
--- a/eric6/ViewManager/ViewManager.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/ViewManager/ViewManager.py Wed Oct 14 17:50:39 2020 +0200 @@ -6583,9 +6583,8 @@ """ if os.path.exists(dictionaryFile): try: - f = open(dictionaryFile, "r", encoding="utf-8") - data = f.read() - f.close() + with open(dictionaryFile, "r", encoding="utf-8") as f: + data = f.read() except (IOError, OSError) as err: E5MessageBox.critical( self.ui, @@ -6613,9 +6612,8 @@ if dlg.exec() == QDialog.Accepted: data = dlg.getData() try: - f = open(dictionaryFile, "w", encoding="utf-8") - f.write(data) - f.close() + with open(dictionaryFile, "w", encoding="utf-8") as f: + f.write(data) except (IOError, OSError) as err: E5MessageBox.critical( self.ui,
--- a/eric6/VirtualEnv/VirtualenvExecDialog.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/VirtualEnv/VirtualenvExecDialog.py Wed Oct 14 17:50:39 2020 +0200 @@ -260,15 +260,14 @@ .format(logFile)) try: - f = open(logFile, "w", encoding="utf-8") - f.write(self.tr("Output:\n")) - f.write(outtxt) - errtxt = self.errors.toPlainText() - if errtxt: - f.write("\n") - f.write(self.tr("Errors:\n")) - f.write(errtxt) - f.close() + with open(logFile, "w", encoding="utf-8") as f: + f.write(self.tr("Output:\n")) + f.write(outtxt) + errtxt = self.errors.toPlainText() + if errtxt: + f.write("\n") + f.write(self.tr("Errors:\n")) + f.write(errtxt) except (IOError, OSError) as err: self.__logError( self.tr("""The logfile '{0}' could not be written.\n""" @@ -294,9 +293,8 @@ .format(script)) try: - f = open(script, "w", encoding="utf-8") - f.write(txt) - f.close() + with open(script, "w", encoding="utf-8") as f: + f.write(txt) except (IOError, OSError) as err: self.__logError( self.tr("""The script file '{0}' could not be written.\n"""
--- a/eric6/WebBrowser/AdBlock/AdBlockSubscription.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/WebBrowser/AdBlock/AdBlockSubscription.py Wed Oct 14 17:50:39 2020 +0200 @@ -471,9 +471,8 @@ @rtype bool """ try: - f = open(fileName, "r", encoding="utf-8") - data = f.read() - f.close() + with open(fileName, "r", encoding="utf-8") as f: + data = f.read() except (IOError, OSError): return False
--- a/eric6/WebBrowser/Bookmarks/BookmarksImporters/ChromeImporter.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/WebBrowser/Bookmarks/BookmarksImporters/ChromeImporter.py Wed Oct 14 17:50:39 2020 +0200 @@ -121,9 +121,8 @@ @return imported bookmarks (BookmarkNode) """ try: - f = open(self.__fileName, "r", encoding="utf-8") - contents = json.load(f) - f.close() + with open(self.__fileName, "r", encoding="utf-8") as f: + contents = json.load(f) except IOError as err: self._error = True self._errorString = self.tr(
--- a/eric6/WebBrowser/Bookmarks/BookmarksImporters/IExplorerImporter.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/WebBrowser/Bookmarks/BookmarksImporters/IExplorerImporter.py Wed Oct 14 17:50:39 2020 +0200 @@ -124,9 +124,8 @@ if ext.lower() == ".url": path = os.path.join(directory, file) try: - f = open(path, "r") - contents = f.read() - f.close() + with open(path, "r") as f: + contents = f.read() except IOError: continue url = ""
--- a/eric6/WebBrowser/Bookmarks/BookmarksImporters/OperaImporter.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/WebBrowser/Bookmarks/BookmarksImporters/OperaImporter.py Wed Oct 14 17:50:39 2020 +0200 @@ -98,9 +98,8 @@ @return imported bookmarks (BookmarkNode) """ try: - f = open(self.__fileName, "r", encoding="utf-8") - contents = f.read() - f.close() + with open(self.__fileName, "r", encoding="utf-8") as f: + contents = f.read() except IOError as err: self._error = True self._errorString = self.tr(
--- a/eric6/WebBrowser/Bookmarks/BookmarksImporters/SafariImporter.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/WebBrowser/Bookmarks/BookmarksImporters/SafariImporter.py Wed Oct 14 17:50:39 2020 +0200 @@ -100,9 +100,8 @@ @return imported bookmarks (BookmarkNode) """ try: - f = open(self.__fileName, "rb") - bookmarksDict = plistlib.load(f) - f.close() + with open(self.__fileName, "rb") as f: + bookmarksDict = plistlib.load(f) except (plistlib.InvalidFileException, EnvironmentError) as err: self._error = True self._errorString = self.tr(
--- a/eric6/WebBrowser/GreaseMonkey/GreaseMonkeyDownloader.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/WebBrowser/GreaseMonkey/GreaseMonkeyDownloader.py Wed Oct 14 17:50:39 2020 +0200 @@ -88,12 +88,11 @@ self.__fileName = WebBrowserTools.ensureUniqueFilename(filePath) try: - f = open(self.__fileName, "w", encoding="utf-8") + with open(self.__fileName, "w", encoding="utf-8") as f: + f.write(response) except (IOError, OSError): self.error.emit() return - f.write(response) - f.close() self.finished.emit(self.__fileName) @@ -144,12 +143,11 @@ self.__fileName) try: - f = open(self.__fileName, "w", encoding="utf-8") + with open(self.__fileName, "w", encoding="utf-8") as f: + f.write(response) except (IOError, OSError): self.error.emit() return - f.write(response) - f.close() settings.setValue(self.__reply.request().url().toString(), QFileInfo(self.__fileName).fileName())
--- a/eric6/WebBrowser/GreaseMonkey/GreaseMonkeyManager.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/WebBrowser/GreaseMonkey/GreaseMonkeyManager.py Wed Oct 14 17:50:39 2020 +0200 @@ -175,9 +175,8 @@ fileName = os.path.join(self.requireScriptsDirectory(), fileName) try: - f = open(fileName, "r", encoding="utf-8") - source = f.read().strip() - f.close() + with open(fileName, "r", encoding="utf-8") as f: + source = f.read().strip() except (IOError, OSError): source = "" if source:
--- a/eric6/WebBrowser/GreaseMonkey/GreaseMonkeyScript.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/WebBrowser/GreaseMonkey/GreaseMonkeyScript.py Wed Oct 14 17:50:39 2020 +0200 @@ -274,9 +274,8 @@ self.__noFrames = False try: - f = open(self.__fileName, "r", encoding="utf-8") - fileData = f.read() - f.close() + with open(self.__fileName, "r", encoding="utf-8") as f: + fileData = f.read() except (IOError, OSError): # silently ignore because it shouldn't happen return
--- a/eric6/WebBrowser/Network/ProtocolHandlerManager.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/WebBrowser/Network/ProtocolHandlerManager.py Wed Oct 14 17:50:39 2020 +0200 @@ -98,9 +98,9 @@ Private method to load the registered protocol handlers. """ try: - protocolHandlersFile = open(self.__protocolHandlersFileName(), "r") - protocolHandlersData = json.load(protocolHandlersFile) - protocolHandlersFile.close() + with open(self.__protocolHandlersFileName(), + "r") as protocolHandlersFile: + protocolHandlersData = json.load(protocolHandlersFile) if protocolHandlersData: self.__protocolHandlers = {} @@ -119,9 +119,9 @@ protocolHandlers = {scheme: url.toString() for scheme, url in self.__protocolHandlers.items()} - protocolHandlersFile = open(self.__protocolHandlersFileName(), "w") - json.dump(protocolHandlers, protocolHandlersFile, indent=2) - protocolHandlersFile.close() + with open(self.__protocolHandlersFileName(), + "w") as protocolHandlersFile: + json.dump(protocolHandlers, protocolHandlersFile, indent=2) def __registerHandler(self, scheme, url): """
--- a/eric6/WebBrowser/Session/SessionManager.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/WebBrowser/Session/SessionManager.py Wed Oct 14 17:50:39 2020 +0200 @@ -210,9 +210,8 @@ ) if sessionData["Windows"]: - sessionFile = open(sessionFileName, "w") - json.dump(sessionData, sessionFile, indent=2) - sessionFile.close() + with open(sessionFileName, "w") as sessionFile: + json.dump(sessionData, sessionFile, indent=2) @classmethod def readSessionFromFile(cls, sessionFileName): @@ -225,9 +224,8 @@ @rtype dict """ try: - sessionFile = open(sessionFileName, "r") - sessionData = json.load(sessionFile) - sessionFile.close() + with open(sessionFileName, "r") as sessionFile: + sessionData = json.load(sessionFile) if not cls.isValidSession(sessionData): sessionData = {} except (IOError, OSError):
--- a/eric6/WebBrowser/Sync/DirectorySyncHandler.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/WebBrowser/Sync/DirectorySyncHandler.py Wed Oct 14 17:50:39 2020 +0200 @@ -89,11 +89,11 @@ """ self.syncStatus.emit(type_, self._messages[type_]["RemoteExists"]) try: - f = open(os.path.join( - Preferences.getWebBrowser("SyncDirectoryPath"), - self._remoteFiles[type_]), "rb") - data = f.read() - f.close() + with open( + os.path.join(Preferences.getWebBrowser("SyncDirectoryPath"), + self._remoteFiles[type_]), "rb" + ) as f: + data = f.read() except IOError as err: self.syncStatus.emit( type_, @@ -125,11 +125,13 @@ return else: try: - f = open(os.path.join( - Preferences.getWebBrowser("SyncDirectoryPath"), - self._remoteFiles[type_]), "wb") - f.write(bytes(data)) - f.close() + with open( + os.path.join( + Preferences.getWebBrowser("SyncDirectoryPath"), + self._remoteFiles[type_]), "wb" + ) as f: + f.write(bytes(data)) + f.close() except IOError as err: self.syncStatus.emit( type_,
--- a/eric6/WebBrowser/Sync/SyncHandler.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/WebBrowser/Sync/SyncHandler.py Wed Oct 14 17:50:39 2020 +0200 @@ -208,9 +208,8 @@ """ if os.path.exists(fileName): try: - inputFile = open(fileName, "rb") - data = inputFile.read() - inputFile.close() + with open(fileName, "rb") as inputFile: + data = inputFile.read() except IOError: return QByteArray() @@ -271,9 +270,8 @@ return False, self.tr("Data cannot be decrypted.") try: - outputFile = open(fileName, "wb") - outputFile.write(data) - outputFile.close() + with open(fileName, "wb") as outputFile: + outputFile.write(data) if timestamp > 0: os.utime(fileName, (timestamp, timestamp)) return True, ""
--- a/eric6/WebBrowser/Tools/WebIconProvider.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/WebBrowser/Tools/WebIconProvider.py Wed Oct 14 17:50:39 2020 +0200 @@ -88,9 +88,8 @@ filename = os.path.join(self.__iconDatabasePath, self.__iconsFileName) try: - f = open(filename, "r") - db = json.load(f) - f.close() + with open(filename, "r") as f: + db = json.load(f) except (IOError, OSError): # ignore silentyl db = {} @@ -122,9 +121,8 @@ filename = os.path.join(self.__iconDatabasePath, self.__iconsFileName) try: - f = open(filename, "w") - json.dump(db, f) - f.close() + with open(filename, "w") as f: + json.dump(db, f) except (IOError, OSError): # ignore silentyl pass
--- a/eric6/eric6.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/eric6.py Wed Oct 14 17:50:39 2020 +0200 @@ -202,10 +202,9 @@ tbinfo] msg = '\n'.join(sections) try: - f = open(logFile, "w", encoding="utf-8") - f.write(msg) - f.write(versionInfo) - f.close() + with open(logFile, "w", encoding="utf-8") as f: + f.write(msg) + f.write(versionInfo) except IOError: pass
--- a/eric6/eric6_api.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/eric6_api.py Wed Oct 14 17:50:39 2020 +0200 @@ -296,18 +296,18 @@ if outdir and not os.path.exists(outdir): os.makedirs(outdir) try: - out = open(outputFile, "w", encoding="utf-8", newline=newline) - out.write("\n".join(sorted(apis)) + "\n") - out.close() + with open(outputFile, "w", encoding="utf-8", + newline=newline) as out: + out.write("\n".join(sorted(apis)) + "\n") except IOError as v: sys.stderr.write("{0} error: {1}\n".format(outputFile, v[1])) sys.exit(3) try: - out = open(basesFile, "w", encoding="utf-8", newline=newline) - for baseEntry in sorted(basesDict.keys()): - out.write("{0} {1}\n".format( - baseEntry, " ".join(sorted(basesDict[baseEntry])))) - out.close() + with open(basesFile, "w", encoding="utf-8", + newline=newline) as out: + for baseEntry in sorted(basesDict.keys()): + out.write("{0} {1}\n".format( + baseEntry, " ".join(sorted(basesDict[baseEntry])))) except IOError as v: sys.stderr.write("{0} error: {1}\n".format(basesFile, v[1])) sys.exit(3)
--- a/eric6/eric6_doc.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/eric6_doc.py Wed Oct 14 17:50:39 2020 +0200 @@ -281,9 +281,8 @@ if stylesheetFile: try: - sf = open(stylesheetFile, "r", encoding="utf-8") - stylesheet = sf.read() - sf.close() + with open(stylesheetFile, "r", encoding="utf-8") as sf: + stylesheet = sf.read() except IOError: sys.stderr.write( "The CSS stylesheet '{0}' does not exist\n".format( @@ -398,9 +397,9 @@ # generate output try: - out = open(f, "w", encoding="utf-8", newline=newline) - out.write(doc) - out.close() + with open(f, "w", encoding="utf-8", + newline=newline) as out: + out.write(doc) except IOError as v: sys.stderr.write("{0} error: {1}\n".format(file, v[1])) else:
--- a/eric6/eric6_post_install.py Tue Oct 13 19:02:26 2020 +0200 +++ b/eric6/eric6_post_install.py Wed Oct 14 17:50:39 2020 +0200 @@ -200,15 +200,13 @@ @param dst destination file name (string) @param scriptsdir directory containing the scripts (string) """ - f = open(src, "r", encoding="utf-8") - text = f.read() - f.close() + with open(src, "r", encoding="utf-8") as f: + text = f.read() text = text.replace("@BINDIR@", scriptsdir) - f = open(dst, "w", encoding="utf-8") - f.write(text) - f.close() + with open(dst, "w", encoding="utf-8") as f: + f.write(text) os.chmod(dst, 0o644) ######################################################################
--- a/scripts/install.py Tue Oct 13 19:02:26 2020 +0200 +++ b/scripts/install.py Wed Oct 14 17:50:39 2020 +0200 @@ -235,9 +235,8 @@ @param name the name of the file. @param text the contents to copy to the file. """ - f = open(name, "w") - f.write(text) - f.close() + with open(name, "w") as f: + f.write(text) def copyDesktopFile(src, dst): @@ -249,17 +248,15 @@ """ global cfg, platBinDir - f = open(src, "r", encoding="utf-8") - text = f.read() - f.close() + with open(src, "r", encoding="utf-8") as f: + text = f.read() text = text.replace("@BINDIR@", platBinDir) text = text.replace("@MARKER@", "") text = text.replace("@PY_MARKER@", "") - f = open(dst, "w", encoding="utf-8") - f.write(text) - f.close() + with open(dst, "w", encoding="utf-8") as f: + f.write(text) os.chmod(dst, 0o644) @@ -279,9 +276,8 @@ else: Version = "Unknown" - f = open(src, "r", encoding="utf-8") - text = f.read() - f.close() + with open(src, "r", encoding="utf-8") as f: + text = f.read() text = ( text.replace("@MARKER@", "") @@ -289,9 +285,8 @@ .replace("@DATE@", time.strftime("%Y-%m-%d")) ) - f = open(dst, "w", encoding="utf-8") - f.write(text) - f.close() + with open(dst, "w", encoding="utf-8") as f: + f.write(text) os.chmod(dst, 0o644) @@ -424,16 +419,15 @@ if not os.path.exists(fname): if not os.path.exists(pdir): os.mkdir(pdir, 0o755) - f = open(fname, "w") - f.write( - '''# -*- coding: utf-8 -*- + with open(fname, "w") as f: + f.write( + '''# -*- coding: utf-8 -*- """ Package containing the global plugins. """ ''' - ) - f.close() + ) os.chmod(fname, 0o644) @@ -1690,9 +1684,8 @@ hgOut = hgOut.strip() if hgOut.endswith("+"): hgOut = hgOut[:-1] - f = open(fileName + ".orig", "r", encoding="utf-8") - text = f.read() - f.close() + with open(fileName + ".orig", "r", encoding="utf-8") as f: + text = f.read() text = ( text.replace("@@REVISION@@", hgOut) .replace("@@VERSION@@", "rev_" + hgOut)
--- a/scripts/patch_modpython.py Tue Oct 13 19:02:26 2020 +0200 +++ b/scripts/patch_modpython.py Wed Oct 14 17:50:39 2020 +0200 @@ -82,41 +82,40 @@ try: filename = os.path.join(modDir, "apache.py") - f = open(filename, "r", encoding="utf-8") + with open(filename, "r", encoding="utf-8") as f: + lines = f.readlines() except EnvironmentError: print("The file {0} does not exist. Aborting.".format(filename)) sys.exit(1) - lines = f.readlines() - f.close() - pdbFound = False ericFound = False sn = "apache.py" - s = open(sn, "w", encoding="utf-8") - for line in lines: - if not pdbFound and line.startswith("import pdb"): - s.write("import eric6.DebugClients.Python.eric6dbgstub as pdb\n") - pdbFound = True - else: - s.write(line) - if line.startswith("import eric6"): - ericFound = True - - if not ericFound: - s.write("\n") - s.write('def initDebugger(name):\n') - s.write(' """\n') - s.write(' Initialize the debugger and set the script name to be' - ' reported \n') - s.write(' by the debugger. This is a patch for eric6.\n') - s.write(' """\n') - s.write(' if not pdb.initDebugger("standard"):\n') - s.write(' raise ImportError("Could not initialize debugger")\n') - s.write(' pdb.setScriptname(name)\n') - s.write("\n") - s.close() + with open(sn, "w", encoding="utf-8") as s: + for line in lines: + if not pdbFound and line.startswith("import pdb"): + s.write("import eric6.DebugClients.Python.eric6dbgstub as" + " pdb\n") + pdbFound = True + else: + s.write(line) + if line.startswith("import eric6"): + ericFound = True + + if not ericFound: + s.write("\n") + s.write('def initDebugger(name):\n') + s.write(' """\n') + s.write(' Initialize the debugger and set the script name to be' + ' reported \n') + s.write(' by the debugger. This is a patch for eric6.\n') + s.write(' """\n') + s.write(' if not pdb.initDebugger("standard"):\n') + s.write(' raise ImportError("Could not initialize' + ' debugger")\n') + s.write(' pdb.setScriptname(name)\n') + s.write("\n") if ericFound: print("Mod_python is already patched for eric6.")
--- a/setup.py Tue Oct 13 19:02:26 2020 +0200 +++ b/setup.py Wed Oct 14 17:50:39 2020 +0200 @@ -145,16 +145,14 @@ hgOut = hgOut.strip() if hgOut.endswith("+"): hgOut = hgOut[:-1] - f = open(fileName + ".orig", "r", encoding="utf-8") - text = f.read() - f.close() + with open(fileName + ".orig", "r", encoding="utf-8") as f: + text = f.read() text = ( text.replace("@@REVISION@@", hgOut) .replace("@@VERSION@@", version) ) - f = open(fileName, "w") - f.write(text) - f.close() + with open(fileName, "w") as f: + f.write(text) else: shutil.copy(fileName + ".orig", fileName) @@ -173,16 +171,14 @@ os.rename(fileName, fileName + ".orig") except EnvironmentError: pass - f = open(fileName + ".orig", "r", encoding="utf-8") - text = f.read() - f.close() + with open(fileName + ".orig", "r", encoding="utf-8") as f: + text = f.read() text = ( text.replace("@VERSION@", version) .replace("@DATE@", datetime.date.today().isoformat()) ) - f = open(fileName, "w") - f.write(text) - f.close() + with open(fileName, "w") as f: + f.write(text) def cleanupSource(dirName):