From dca3f2c1b9aed2595923bdae47e4e2600f71104c Mon Sep 17 00:00:00 2001 From: Ned Batchelder Date: Fri, 24 Nov 2023 06:54:51 -0500 Subject: [PATCH] refactor: use `with` to open files --- cogapp/cogapp.py | 3 ++- cogapp/test_cogapp.py | 19 +++++++++---------- cogapp/test_makefiles.py | 10 ++++------ 3 files changed, 15 insertions(+), 17 deletions(-) diff --git a/cogapp/cogapp.py b/cogapp/cogapp.py index fb41754..ae76743 100644 --- a/cogapp/cogapp.py +++ b/cogapp/cogapp.py @@ -650,7 +650,8 @@ def replaceFile(self, sOldPath, sNewText): if self.options.sMakeWritableCmd: # Use an external command to make the file writable. cmd = self.options.sMakeWritableCmd.replace('%s', sOldPath) - self.stdout.write(os.popen(cmd).read()) + with os.popen(cmd) as cmdout: + self.stdout.write(cmdout.read()) if not os.access(sOldPath, os.W_OK): raise CogError(f"Couldn't make {sOldPath} writable") else: diff --git a/cogapp/test_cogapp.py b/cogapp/test_cogapp.py index 458c8ba..7a70582 100644 --- a/cogapp/test_cogapp.py +++ b/cogapp/test_cogapp.py @@ -782,18 +782,17 @@ def tearDown(self): shutil.rmtree(self.tempdir) def assertFilesSame(self, sFName1, sFName2): - text1 = open(os.path.join(self.tempdir, sFName1), 'rb').read() - text2 = open(os.path.join(self.tempdir, sFName2), 'rb').read() + with open(os.path.join(self.tempdir, sFName1), 'rb') as f1: + text1 = f1.read() + with open(os.path.join(self.tempdir, sFName2), 'rb') as f2: + text2 = f2.read() self.assertEqual(text1, text2) - def assertFileContent(self, sFName, sContent): - sAbsName = os.path.join(self.tempdir, sFName) - f = open(sAbsName, 'rb') - try: - sFileContent = f.read() - finally: - f.close() - self.assertEqual(sFileContent, sContent.encode("utf-8")) + def assertFileContent(self, fname, content): + absname = os.path.join(self.tempdir, fname) + with open(absname, 'rb') as f: + file_content = f.read() + self.assertEqual(file_content, content.encode("utf-8")) class ArgumentHandlingTests(TestCaseWithTempDir): diff --git a/cogapp/test_makefiles.py b/cogapp/test_makefiles.py index e0b9bf2..806ff86 100644 --- a/cogapp/test_makefiles.py +++ b/cogapp/test_makefiles.py @@ -97,9 +97,8 @@ def testContents(self): cont0 = "I am bar.txt" d = { fname: cont0 } makefiles.makeFiles(d, self.tempdir) - fcont1 = open(os.path.join(self.tempdir, fname)) - assert(fcont1.read() == cont0) - fcont1.close() + with open(os.path.join(self.tempdir, fname)) as fcont1: + assert(fcont1.read() == cont0) def testDedent(self): fname = 'dedent.txt' @@ -112,6 +111,5 @@ def testDedent(self): """, } makefiles.makeFiles(d, self.tempdir) - fcont = open(os.path.join(self.tempdir, fname)) - assert(fcont.read() == "This is dedent.txt\n\tTabbed in.\n spaced in.\nOK.\n") - fcont.close() + with open(os.path.join(self.tempdir, fname)) as fcont: + assert(fcont.read() == "This is dedent.txt\n\tTabbed in.\n spaced in.\nOK.\n")