← Back to team overview

launchpad-reviewers team mailing list archive

[Merge] ~cjwatson/launchpad:open-not-file into launchpad:master

 

Colin Watson has proposed merging ~cjwatson/launchpad:open-not-file into launchpad:master.

Commit message:
Use open() rather than file()

Requested reviews:
  Launchpad code reviewers (launchpad-reviewers)

For more details, see:
https://code.launchpad.net/~cjwatson/launchpad/+git/launchpad/+merge/380385

Also convert to the context manager form where appropriate.
-- 
Your team Launchpad code reviewers is requested to review the proposed merge of ~cjwatson/launchpad:open-not-file into launchpad:master.
diff --git a/lib/lp/app/browser/launchpad.py b/lib/lp/app/browser/launchpad.py
index 4aa9a39..e1a5c71 100644
--- a/lib/lp/app/browser/launchpad.py
+++ b/lib/lp/app/browser/launchpad.py
@@ -544,7 +544,8 @@ class MaintenanceMessage:
 
     def __call__(self):
         if os.path.exists('+maintenancetime.txt'):
-            message = file('+maintenancetime.txt').read()
+            with open('+maintenancetime.txt') as f:
+                message = f.read()
             try:
                 maintenancetime = parseDatetimetz(message)
             except DateTimeError:
diff --git a/lib/lp/app/stories/basics/xx-maintenance-message.txt b/lib/lp/app/stories/basics/xx-maintenance-message.txt
index 776abf9..db47ea2 100644
--- a/lib/lp/app/stories/basics/xx-maintenance-message.txt
+++ b/lib/lp/app/stories/basics/xx-maintenance-message.txt
@@ -73,14 +73,16 @@ When the time is in the past, the time is still given as "very very soon".
 
 If the time doesn't make sense, or is empty, then no message is displayed.
 
-    >>> file('+maintenancetime.txt', 'w').write('xxxx')
+    >>> with open('+maintenancetime.txt', 'w') as f:
+    ...     f.write('xxxx')
     >>> content = front_page_content()
     >>> okay200 in content
     True
     >>> maintenance_text not in content
     True
 
-    >>> file('+maintenancetime.txt', 'w').write('')
+    >>> with open('+maintenancetime.txt', 'w') as f:
+    ...     f.write('')
     >>> content = front_page_content()
     >>> okay200 in content
     True
diff --git a/lib/lp/app/stories/folder.txt b/lib/lp/app/stories/folder.txt
index b66678a..7764753 100644
--- a/lib/lp/app/stories/folder.txt
+++ b/lib/lp/app/stories/folder.txt
@@ -12,14 +12,15 @@ the directory to expose.
     >>> import os
     >>> import tempfile
     >>> resource_dir = tempfile.mkdtemp(prefix='resources')
-    >>> file(os.path.join(resource_dir, 'test.txt'), 'w').write('Text file')
-    >>> file(os.path.join(resource_dir, 'image1.gif'), 'w').write(
-    ...     'GIF file')
-    >>> file(os.path.join(resource_dir, 'image2.png'), 'w').write(
-    ...     'PNG file')
+    >>> with open(os.path.join(resource_dir, 'test.txt'), 'w') as f:
+    ...     f.write('Text file')
+    >>> with open(os.path.join(resource_dir, 'image1.gif'), 'w') as f:
+    ...     f.write('GIF file')
+    >>> with open(os.path.join(resource_dir, 'image2.png'), 'w') as f:
+    ...     f.write('PNG file')
     >>> os.mkdir(os.path.join(resource_dir, 'a_dir'))
-    >>> file(os.path.join(resource_dir, 'other.txt'), 'w').write(
-    ...     'Other file')
+    >>> with open(os.path.join(resource_dir, 'other.txt'), 'w') as f:
+    ...     f.write('Other file')
 
     >>> from lp.app.browser.folder import ExportedFolder
     >>> class MyFolder(ExportedFolder):
@@ -123,10 +124,10 @@ image_extensions property.
 
 If a file without extension exists, that one will be served.
 
-    >>> file(os.path.join(resource_dir, 'image3'), 'w').write(
-    ...     'Image without extension')
-    >>> file(os.path.join(resource_dir, 'image3.gif'), 'w').write(
-    ...     'Image with extension')
+    >>> with open(os.path.join(resource_dir, 'image3'), 'w') as f:
+    ...     f.write('Image without extension')
+    >>> with open(os.path.join(resource_dir, 'image3.gif'), 'w') as f:
+    ...     f.write('Image with extension')
 
     >>> view = MyImageFolder(object(), FakeRequest(version="devel"))
     >>> view = view.publishTraverse(view.request, 'image3')
@@ -146,12 +147,13 @@ export_subdirectories is set to True, it will allow traversing to
 subdirectories.
 
     >>> os.mkdir(os.path.join(resource_dir, 'public'))
-    >>> file(os.path.join(
-    ...     resource_dir, 'public', 'test1.txt'), 'w').write('Public File')
+    >>> with open(os.path.join(
+    ...         resource_dir, 'public', 'test1.txt'), 'w') as f:
+    ...     f.write('Public File')
     >>> os.mkdir(os.path.join(resource_dir, 'public', 'subdir1'))
-    >>> file(os.path.join(
-    ...     resource_dir, 'public', 'subdir1', 'test1.txt'), 'w').write(
-    ...         'Sub file 1')
+    >>> with open(os.path.join(
+    ...         resource_dir, 'public', 'subdir1', 'test1.txt'), 'w') as f:
+    ...     f.write('Sub file 1')
 
     >>> class MyTree(ExportedFolder):
     ...     folder = resource_dir
diff --git a/lib/lp/archivepublisher/scripts/generate_contents_files.py b/lib/lp/archivepublisher/scripts/generate_contents_files.py
index d99258e..4893523 100644
--- a/lib/lp/archivepublisher/scripts/generate_contents_files.py
+++ b/lib/lp/archivepublisher/scripts/generate_contents_files.py
@@ -48,9 +48,10 @@ def differ_in_content(one_file, other_file):
     one_exists = file_exists(one_file)
     other_exists = file_exists(other_file)
     if any([one_exists, other_exists]):
-        return (
-            one_exists != other_exists or
-            file(one_file).read() != file(other_file).read())
+        if one_exists != other_exists:
+            return True
+        with open(one_file, 'rb') as one_f, open(other_file, 'rb') as other_f:
+            return one_f.read() != other_f.read()
     else:
         return False
 
@@ -161,23 +162,24 @@ class GenerateContentsFiles(LaunchpadCronScript):
         output_dirname = '%s-misc' % self.distribution.name
         output_path = os.path.join(
             self.content_archive, output_dirname, "apt-contents.conf")
-        output_file = file(output_path, 'w')
 
         parameters = {
             'content_archive': self.content_archive,
             'distribution': self.distribution.name,
         }
 
-        header = get_template('apt_conf_header.template')
-        output_file.write(file(header).read() % parameters)
-
-        dist_template = file(get_template('apt_conf_dist.template')).read()
-        for suite in suites:
-            parameters['suite'] = suite
-            parameters['architectures'] = ' '.join(self.getArchs(suite))
-            output_file.write(dist_template % parameters)
-
-        output_file.close()
+        with open(output_path, 'w') as output_file:
+            header = get_template('apt_conf_header.template')
+            with open(header) as header_file:
+                output_file.write(header_file.read() % parameters)
+
+            with open(get_template(
+                    'apt_conf_dist.template')) as dist_template_file:
+                dist_template = dist_template_file.read()
+            for suite in suites:
+                parameters['suite'] = suite
+                parameters['architectures'] = ' '.join(self.getArchs(suite))
+                output_file.write(dist_template % parameters)
 
     def createComponentDirs(self, suites):
         """Create the content archive's tree for all of its components."""
diff --git a/lib/lp/archivepublisher/scripts/publish_ftpmaster.py b/lib/lp/archivepublisher/scripts/publish_ftpmaster.py
index 47aa73d..5fcd7d3 100644
--- a/lib/lp/archivepublisher/scripts/publish_ftpmaster.py
+++ b/lib/lp/archivepublisher/scripts/publish_ftpmaster.py
@@ -238,7 +238,7 @@ class PublishFTPMaster(LaunchpadCronScript):
         longer needs archive indexes to be set up.
         """
         marker_name = self.locateIndexesMarker(distribution, suite)
-        with file(marker_name, "w") as marker:
+        with open(marker_name, "w") as marker:
             marker.write(
                 "Indexes for %s were created on %s.\n"
                 % (suite, datetime.now(utc)))
diff --git a/lib/lp/archivepublisher/tests/test_ftparchive.py b/lib/lp/archivepublisher/tests/test_ftparchive.py
index 5e77ec4..a8a6727 100755
--- a/lib/lp/archivepublisher/tests/test_ftparchive.py
+++ b/lib/lp/archivepublisher/tests/test_ftparchive.py
@@ -156,8 +156,10 @@ class TestFTPArchive(TestCaseWithFactory):
         if samplename is None:
             samplename = leafname
         leaf = os.path.join(self._sampledir, samplename)
-        leafcontent = file(leaf).read()
-        file(fullpath, "w").write(leafcontent)
+        with open(leaf) as leaf_file:
+            leafcontent = leaf_file.read()
+        with open(fullpath, "w") as f:
+            f.write(leafcontent)
 
     def _setUpFTPArchiveHandler(self):
         return FTPArchiveHandler(
@@ -483,7 +485,8 @@ class TestFTPArchive(TestCaseWithFactory):
         # Test that a publisher run now will generate an empty apt
         # config and nothing else.
         apt_conf = fa.generateConfig()
-        self.assertEqual(22, len(file(apt_conf).readlines()))
+        with open(apt_conf) as apt_conf_file:
+            self.assertEqual(22, len(apt_conf_file.readlines()))
 
         # XXX cprov 2007-03-21: see above, do not run a-f on dev machines.
         fa.runApt(apt_conf)
@@ -532,10 +535,11 @@ class TestFTPArchive(TestCaseWithFactory):
         # comparing is weak.
         apt_conf = fa.generateConfig(fullpublish=True)
         self.assertTrue(os.path.exists(apt_conf))
-        apt_conf_content = file(apt_conf).read()
-        sample_content = file(
-            os.path.join(
-            self._sampledir, 'apt_conf_single_empty_suite_test')).read()
+        with open(apt_conf) as apt_conf_file:
+            apt_conf_content = apt_conf_file.read()
+        with open(os.path.join(
+                self._sampledir, 'apt_conf_single_empty_suite_test')) as f:
+            sample_content = f.read()
         self.assertEqual(apt_conf_content, sample_content)
 
         # XXX cprov 2007-03-21: see above, do not run a-f on dev machines.
diff --git a/lib/lp/archivepublisher/tests/test_generate_contents_files.py b/lib/lp/archivepublisher/tests/test_generate_contents_files.py
index cb75954..4534570 100644
--- a/lib/lp/archivepublisher/tests/test_generate_contents_files.py
+++ b/lib/lp/archivepublisher/tests/test_generate_contents_files.py
@@ -231,9 +231,10 @@ class TestGenerateContentsFiles(TestCaseWithFactory):
         distro = self.makeDistro()
         script = self.makeScript(distro)
         script.writeAptContentsConf([])
-        apt_contents_conf = file(
-            "%s/%s-misc/apt-contents.conf"
-            % (script.content_archive, distro.name)).read()
+        with open(
+                "%s/%s-misc/apt-contents.conf"
+                % (script.content_archive, distro.name)) as f:
+            apt_contents_conf = f.read()
         self.assertIn('\nDefault\n{', apt_contents_conf)
         self.assertIn(distro.name, apt_contents_conf)
 
@@ -247,9 +248,10 @@ class TestGenerateContentsFiles(TestCaseWithFactory):
         script = self.makeScript(distro)
         content_archive = script.content_archive
         script.writeAptContentsConf([distroseries.name])
-        apt_contents_conf = file(
-            "%s/%s-misc/apt-contents.conf"
-            % (script.content_archive, distro.name)).read()
+        with open(
+                "%s/%s-misc/apt-contents.conf"
+                % (script.content_archive, distro.name)) as f:
+            apt_contents_conf = f.read()
         self.assertIn(
             'tree "dists/%s"\n' % distroseries.name, apt_contents_conf)
         overrides_path = os.path.join(
diff --git a/lib/lp/archivepublisher/tests/test_publish_ftpmaster.py b/lib/lp/archivepublisher/tests/test_publish_ftpmaster.py
index d20c7a8..8c99b73 100644
--- a/lib/lp/archivepublisher/tests/test_publish_ftpmaster.py
+++ b/lib/lp/archivepublisher/tests/test_publish_ftpmaster.py
@@ -214,7 +214,8 @@ class TestPublishFTPMasterScript(
 
     def readReleaseFile(self, filename):
         """Read a Release file, return as a keyword/value dict."""
-        sections = list(TagFile(file(filename)))
+        with open(filename) as f:
+            sections = list(TagFile(f))
         self.assertEqual(1, len(sections))
         return dict(sections[0])
 
@@ -233,9 +234,8 @@ class TestPublishFTPMasterScript(
         script_dir = os.path.join(parts_base, distro.name, parts_dir)
         os.makedirs(script_dir)
         script_path = os.path.join(script_dir, self.factory.getUniqueString())
-        script_file = file(script_path, "w")
-        script_file.write(script_code)
-        script_file.close()
+        with open(script_path, "w") as script_file:
+            script_file.write(script_code)
         os.chmod(script_path, 0o755)
 
     def test_script_runs_successfully(self):
@@ -308,10 +308,12 @@ class TestPublishFTPMasterScript(
 
         dsc = os.path.join(
             archive_root, 'pool', 'main', 'f', 'foo', 'foo_666.dsc')
-        self.assertEqual("I do not care about sources.", file(dsc).read())
+        with open(dsc) as dsc_file:
+            self.assertEqual("I do not care about sources.", dsc_file.read())
         overrides = os.path.join(
             archive_root + '-overrides', distroseries.name + '_main_source')
-        self.assertEqual(dsc, file(overrides).read().rstrip())
+        with open(overrides) as overrides_file:
+            self.assertEqual(dsc, overrides_file.read().rstrip())
         self.assertTrue(path_exists(
             dists_root, distroseries.name, 'main', 'source', 'Sources.gz'))
         self.assertTrue(path_exists(
diff --git a/lib/lp/services/config/__init__.py b/lib/lp/services/config/__init__.py
index ae94cf0..3c6ad51 100644
--- a/lib/lp/services/config/__init__.py
+++ b/lib/lp/services/config/__init__.py
@@ -73,8 +73,8 @@ def find_instance_name():
     if instance_name is None:
         for config_lookup_file in CONFIG_LOOKUP_FILES:
             if os.path.exists(config_lookup_file):
-                instance_name = file(
-                    config_lookup_file, 'r').read()[:80].strip()
+                with open(config_lookup_file) as f:
+                    instance_name = f.read()[:80].strip()
                 break
 
     # Of instance_name falls back for developers.
diff --git a/lib/lp/services/profile/mem.py b/lib/lp/services/profile/mem.py
index 19bc988..73ea820 100644
--- a/lib/lp/services/profile/mem.py
+++ b/lib/lp/services/profile/mem.py
@@ -207,7 +207,7 @@ def readCounts(file, marker=None):
 
 
 def logInThread(n=30):
-    reflog = file('/tmp/refs.log', 'w')
+    reflog = open('/tmp/refs.log', 'w')
     t = threading.Thread(target=_logRefsEverySecond, args=(reflog, n))
     # Allow process to exit without explicitly stopping thread.
     t.daemon = True
diff --git a/lib/lp/services/profile/profile.py b/lib/lp/services/profile/profile.py
index c44778a..400f96e 100644
--- a/lib/lp/services/profile/profile.py
+++ b/lib/lp/services/profile/profile.py
@@ -354,15 +354,14 @@ def end_request(event):
         del prof_stats
     # Dump memory profiling info.
     if 'memory_profile_start' in actions:
-        log = file(config.profiling.memory_profile_log, 'a')
-        vss_start, rss_start = actions.pop('memory_profile_start')
-        vss_end, rss_end = memory(), resident()
-        if oopsid is None:
-            oopsid = '-'
-        log.write('%s %s %s %f %d %d %d %d\n' % (
-            timestamp, pageid, oopsid, da.get_request_duration(),
-            vss_start, rss_start, vss_end, rss_end))
-        log.close()
+        with open(config.profiling.memory_profile_log, 'a') as log:
+            vss_start, rss_start = actions.pop('memory_profile_start')
+            vss_end, rss_end = memory(), resident()
+            if oopsid is None:
+                oopsid = '-'
+            log.write('%s %s %s %f %d %d %d %d\n' % (
+                timestamp, pageid, oopsid, da.get_request_duration(),
+                vss_start, rss_start, vss_end, rss_end))
     trace = None
     if 'sql' in actions:
         trace = da.stop_sql_logging() or ()
diff --git a/lib/lp/services/profile/profiling.txt b/lib/lp/services/profile/profiling.txt
index 9a16054..844698b 100644
--- a/lib/lp/services/profile/profiling.txt
+++ b/lib/lp/services/profile/profiling.txt
@@ -195,10 +195,10 @@ log file.
     ...     profile_request: False
     ...     memory_profile_log: %s""" % memory_profile_log))
     >>> response = http('GET / HTTP/1.0')
-    >>> memory_profile_fh = file(memory_profile_log)
-    >>> (timestamp, page_id, oops_id, duration,
-    ...  start_vss, start_rss, end_vss, end_rss) = (
-    ...     memory_profile_fh.readline().split())
+    >>> with open(memory_profile_log) as memory_profile_fh:
+    ...     (timestamp, page_id, oops_id, duration,
+    ...      start_vss, start_rss, end_vss, end_rss) = (
+    ...         memory_profile_fh.readline().split())
     >>> print timestamp
     20...
     >>> print oops_id
diff --git a/lib/lp/services/sitesearch/tests/test_testservices.py b/lib/lp/services/sitesearch/tests/test_testservices.py
index 83130c0..2474003 100644
--- a/lib/lp/services/sitesearch/tests/test_testservices.py
+++ b/lib/lp/services/sitesearch/tests/test_testservices.py
@@ -36,7 +36,7 @@ class TestServiceUtilities(WithScenarios, unittest.TestCase):
 
         # Create a stale/bogus PID file.
         filepath = pidfile_path(self.testservice.service_name)
-        with file(filepath, 'w') as pidfile:
+        with open(filepath, 'w') as pidfile:
             pidfile.write(str(bogus_pid))
 
         # The PID clean-up code should silently remove the file and return.
diff --git a/lib/lp/services/sitesearch/testservice.py b/lib/lp/services/sitesearch/testservice.py
index 72c3aeb..430bb85 100644
--- a/lib/lp/services/sitesearch/testservice.py
+++ b/lib/lp/services/sitesearch/testservice.py
@@ -49,7 +49,8 @@ class RequestHandler(BaseHTTPRequestHandler):
         self.end_headers()
 
         filepath = os.path.join(self.content_dir, filename)
-        content_body = file(filepath).read()
+        with open(filepath) as f:
+            content_body = f.read()
         self.wfile.write(content_body)
 
     def log_message(self, format, *args):
@@ -66,12 +67,13 @@ class RequestHandler(BaseHTTPRequestHandler):
 def url_to_file_map(mapfile):
     """Return our URL-to-file mapping as a dictionary."""
     mapping = {}
-    for line in file(mapfile):
-        if line.startswith('#') or len(line.strip()) == 0:
-            # Skip comments and blank lines.
-            continue
-        url, fname = line.split()
-        mapping[url.strip()] = fname.strip()
+    with open(mapfile) as f:
+        for line in f:
+            if line.startswith('#') or len(line.strip()) == 0:
+                # Skip comments and blank lines.
+                continue
+            url, fname = line.split()
+            mapping[url.strip()] = fname.strip()
 
     return mapping
 
diff --git a/lib/lp/services/tests/test_utils.py b/lib/lp/services/tests/test_utils.py
index e753a82..02922bb 100644
--- a/lib/lp/services/tests/test_utils.py
+++ b/lib/lp/services/tests/test_utils.py
@@ -346,7 +346,8 @@ class TestFileExists(TestCase):
         self.useTempDir()
 
     def test_finds_file(self):
-        file("a-real-file.txt", "w").write("Here I am.")
+        with open("a-real-file.txt", "w") as f:
+            f.write("Here I am.")
         self.assertTrue(file_exists("a-real-file.txt"))
 
     def test_finds_directory(self):
diff --git a/lib/lp/soyuz/scripts/gina/changelog.py b/lib/lp/soyuz/scripts/gina/changelog.py
index ab6ce3a..bd637da 100644
--- a/lib/lp/soyuz/scripts/gina/changelog.py
+++ b/lib/lp/soyuz/scripts/gina/changelog.py
@@ -100,4 +100,5 @@ def parse_changelog(changelines):
 
 if __name__ == '__main__':
     import pprint
-    pprint.pprint(parse_changelog(file(sys.argv[1], "r")))
+    with open(sys.argv[1]) as f:
+        pprint.pprint(parse_changelog(f))
diff --git a/lib/lp/translations/scripts/language_pack.py b/lib/lp/translations/scripts/language_pack.py
index 34d28c7..5e38bc8 100644
--- a/lib/lp/translations/scripts/language_pack.py
+++ b/lib/lp/translations/scripts/language_pack.py
@@ -251,9 +251,12 @@ def export_language_pack(distribution_name, series_name, logger,
         if output_file == '-':
             output_filehandle = sys.stdout
         else:
-            output_filehandle = file(output_file, 'wb')
+            output_filehandle = open(output_file, 'wb')
 
         copyfileobj(filehandle, output_filehandle)
+
+        if output_filehandle != sys.stdout:
+            output_filehandle.close()
     else:
         # Upload the tarball to the librarian.
 
diff --git a/lib/lp/translations/scripts/validate_translations_file.py b/lib/lp/translations/scripts/validate_translations_file.py
index bcf2ff6..d828dc3 100644
--- a/lib/lp/translations/scripts/validate_translations_file.py
+++ b/lib/lp/translations/scripts/validate_translations_file.py
@@ -128,5 +128,6 @@ class ValidateTranslationsFile:
         :param filename: Name of a file to read.
         :return: Whether the file was parsed successfully.
         """
-        content = file(filename).read()
+        with open(filename) as f:
+            content = f.read()
         return self._validateContent(filename, content)
diff --git a/lib/lp/translations/tests/test_translationtemplatesbuildbehaviour.py b/lib/lp/translations/tests/test_translationtemplatesbuildbehaviour.py
index 32dd553..525ff4a 100644
--- a/lib/lp/translations/tests/test_translationtemplatesbuildbehaviour.py
+++ b/lib/lp/translations/tests/test_translationtemplatesbuildbehaviour.py
@@ -297,8 +297,8 @@ class TestTTBuildBehaviourTranslationsQueue(
     def test_uploadTarball(self):
         # Files from the tarball end up in the import queue.
         behaviour = self.makeBehaviour()
-        behaviour._uploadTarball(
-            self.branch, file(self.dummy_tar).read(), None)
+        with open(self.dummy_tar) as f:
+            behaviour._uploadTarball(self.branch, f.read(), None)
 
         entries = self.queue.getAllEntries(target=self.productseries)
         expected_templates = [
@@ -313,8 +313,8 @@ class TestTTBuildBehaviourTranslationsQueue(
     def test_uploadTarball_approved(self):
         # Uploaded template files are automatically approved.
         behaviour = self.makeBehaviour()
-        behaviour._uploadTarball(
-            self.branch, file(self.dummy_tar).read(), None)
+        with open(self.dummy_tar) as f:
+            behaviour._uploadTarball(self.branch, f.read(), None)
 
         entries = self.queue.getAllEntries(target=self.productseries)
         statuses = [entry.status for entry in entries]
@@ -324,8 +324,8 @@ class TestTTBuildBehaviourTranslationsQueue(
     def test_uploadTarball_importer(self):
         # Files from the tarball are owned by the branch owner.
         behaviour = self.makeBehaviour()
-        behaviour._uploadTarball(
-            self.branch, file(self.dummy_tar).read(), None)
+        with open(self.dummy_tar) as f:
+            behaviour._uploadTarball(self.branch, f.read(), None)
 
         entries = self.queue.getAllEntries(target=self.productseries)
         self.assertEqual(self.branch.owner, entries[0].importer)
diff --git a/scripts/process-one-mail.py b/scripts/process-one-mail.py
index c2caab6..420f0f1 100755
--- a/scripts/process-one-mail.py
+++ b/scripts/process-one-mail.py
@@ -30,11 +30,13 @@ class ProcessMail(LaunchpadScript):
         # NB: This somewhat duplicates handleMail, but there it's mixed in
         # with handling a mailbox, which we're avoiding here.
         if len(self.args) >= 1:
-            from_file = file(self.args[0], 'rb')
+            from_file = open(self.args[0], 'rb')
         else:
             from_file = sys.stdin
         self.logger.debug("reading message from %r" % (from_file,))
         raw_mail = from_file.read()
+        if from_file != sys.stdin:
+            from_file.close()
         self.logger.debug("got %d bytes" % len(raw_mail))
         file_alias = save_mail_to_librarian(raw_mail)
         self.logger.debug("saved to librarian as %r" % (file_alias,))
diff --git a/utilities/audit-security-settings.py b/utilities/audit-security-settings.py
index 1095c3e..f045b34 100755
--- a/utilities/audit-security-settings.py
+++ b/utilities/audit-security-settings.py
@@ -25,10 +25,12 @@ SECURITY_PATH = os.path.join(
 
 
 def main():
-    data = file(SECURITY_PATH).read()
+    with open(SECURITY_PATH) as f:
+        data = f.read()
     auditor = SettingsAuditor(data)
     settings = auditor.audit()
-    file(SECURITY_PATH, 'w').write(settings)
+    with open(SECURITY_PATH, 'w') as f:
+        f.write(settings)
     print auditor.error_data
 
 if __name__ == '__main__':
diff --git a/utilities/format-imports b/utilities/format-imports
index 49cf195..f59679b 100755
--- a/utilities/format-imports
+++ b/utilities/format-imports
@@ -345,7 +345,8 @@ def format_imports(imports):
 
 def reformat_importsection(filename):
     """Replace the given file with a reformatted version of it."""
-    pyfile = file(filename).read()
+    with open(filename) as f:
+        pyfile = f.read()
     import_start, import_end = find_imports_section(pyfile)
     if import_start is None:
         # Skip files with no import section.
diff --git a/utilities/update-copyright b/utilities/update-copyright
index c2e0236..8302316 100755
--- a/utilities/update-copyright
+++ b/utilities/update-copyright
@@ -55,7 +55,8 @@ def update_files(filenames):
         if not os.access(filename, os.W_OK):
             print "Skipped: %s is not writeable." % filename
             continue
-        lines = file(filename).readlines()
+        with open(filename) as f:
+            lines = f.readlines()
         changed = update_copyright(lines)
         if changed:
             newfile = open(filename, 'w')