Index: Lib/modulefinder.py =================================================================== --- Lib/modulefinder.py (revision 60326) +++ Lib/modulefinder.py (working copy) @@ -109,16 +109,16 @@ def run_script(self, pathname): self.msg(2, "run_script", pathname) - fp = open(pathname, READ_MODE) - stuff = ("", "r", imp.PY_SOURCE) - self.load_module('__main__', fp, pathname, stuff) + with open(pathname, READ_MODE) as fp: + stuff = ("", "r", imp.PY_SOURCE) + self.load_module('__main__', fp, pathname, stuff) def load_file(self, pathname): dir, name = os.path.split(pathname) name, ext = os.path.splitext(name) - fp = open(pathname, READ_MODE) - stuff = (ext, "r", imp.PY_SOURCE) - self.load_module(name, fp, pathname, stuff) + with open(pathname, READ_MODE) as fp: + stuff = (ext, "r", imp.PY_SOURCE) + self.load_module(name, fp, pathname, stuff) def import_hook(self, name, caller=None, fromlist=None, level=-1): self.msg(3, "import_hook", name, caller, fromlist, level) Index: Lib/ftplib.py =================================================================== --- Lib/ftplib.py (revision 60326) +++ Lib/ftplib.py (working copy) @@ -712,60 +712,59 @@ "specify file to load or set $HOME" self.__hosts = {} self.__macros = {} - fp = open(filename, "r") - in_macro = 0 - while 1: - line = fp.readline() - if not line: break - if in_macro and line.strip(): - macro_lines.append(line) - continue - elif in_macro: - self.__macros[macro_name] = tuple(macro_lines) - in_macro = 0 - words = line.split() - host = user = passwd = acct = None - default = 0 - i = 0 - while i < len(words): - w1 = words[i] - if i+1 < len(words): - w2 = words[i + 1] - else: - w2 = None - if w1 == 'default': - default = 1 - elif w1 == 'machine' and w2: - host = w2.lower() + with open(filename, "r") as fp: + in_macro = 0 + while 1: + line = fp.readline() + if not line: break + if in_macro and line.strip(): + macro_lines.append(line) + continue + elif in_macro: + self.__macros[macro_name] = tuple(macro_lines) + in_macro = 0 + words = line.split() + host = user = passwd = acct = None + default = 0 + i = 0 + while i < len(words): + w1 = words[i] + if i+1 < len(words): + w2 = words[i + 1] + else: + w2 = None + if w1 == 'default': + default = 1 + elif w1 == 'machine' and w2: + host = w2.lower() + i = i + 1 + elif w1 == 'login' and w2: + user = w2 + i = i + 1 + elif w1 == 'password' and w2: + passwd = w2 + i = i + 1 + elif w1 == 'account' and w2: + acct = w2 + i = i + 1 + elif w1 == 'macdef' and w2: + macro_name = w2 + macro_lines = [] + in_macro = 1 + break i = i + 1 - elif w1 == 'login' and w2: - user = w2 - i = i + 1 - elif w1 == 'password' and w2: - passwd = w2 - i = i + 1 - elif w1 == 'account' and w2: - acct = w2 - i = i + 1 - elif w1 == 'macdef' and w2: - macro_name = w2 - macro_lines = [] - in_macro = 1 - break - i = i + 1 - if default: - self.__defuser = user or self.__defuser - self.__defpasswd = passwd or self.__defpasswd - self.__defacct = acct or self.__defacct - if host: - if host in self.__hosts: - ouser, opasswd, oacct = \ - self.__hosts[host] - user = user or ouser - passwd = passwd or opasswd - acct = acct or oacct - self.__hosts[host] = user, passwd, acct - fp.close() + if default: + self.__defuser = user or self.__defuser + self.__defpasswd = passwd or self.__defpasswd + self.__defacct = acct or self.__defacct + if host: + if host in self.__hosts: + ouser, opasswd, oacct = \ + self.__hosts[host] + user = user or ouser + passwd = passwd or opasswd + acct = acct or oacct + self.__hosts[host] = user, passwd, acct def get_hosts(self): """Return a list of hosts mentioned in the .netrc file.""" Index: Lib/cookielib.py =================================================================== --- Lib/cookielib.py (revision 60326) +++ Lib/cookielib.py (working copy) @@ -1753,11 +1753,8 @@ if self.filename is not None: filename = self.filename else: raise ValueError(MISSING_FILENAME_TEXT) - f = open(filename) - try: + with open(filename) as f: self._really_load(f, filename, ignore_discard, ignore_expires) - finally: - f.close() def revert(self, filename=None, ignore_discard=False, ignore_expires=False): Index: Lib/shutil.py =================================================================== --- Lib/shutil.py (revision 60326) +++ Lib/shutil.py (working copy) @@ -8,6 +8,7 @@ import sys import stat from os.path import abspath +from contextlib import nested __all__ = ["copyfileobj","copyfile","copymode","copystat","copy","copy2", "copytree","move","rmtree","Error"] @@ -42,15 +43,8 @@ fsrc = None fdst = None - try: - fsrc = open(src, 'rb') - fdst = open(dst, 'wb') + with nested(open(src, 'rb'), open(dst, 'wb')) as (fsrc, fdst): copyfileobj(fsrc, fdst) - finally: - if fdst: - fdst.close() - if fsrc: - fsrc.close() def copymode(src, dst): """Copy mode bits from src to dst""" Index: Lib/pydoc.py =================================================================== --- Lib/pydoc.py (revision 60326) +++ Lib/pydoc.py (working copy) @@ -244,20 +244,18 @@ def importfile(path): """Import a Python source file or compiled file given its path.""" magic = imp.get_magic() - file = open(path, 'r') - if file.read(len(magic)) == magic: - kind = imp.PY_COMPILED - else: - kind = imp.PY_SOURCE - file.close() + with open(path, 'r') as file: + if file.read(len(magic)) == magic: + kind = imp.PY_COMPILED + else: + kind = imp.PY_SOURCE filename = os.path.basename(path) name, ext = os.path.splitext(filename) - file = open(path, 'r') - try: - module = imp.load_module(name, file, path, (ext, 'r', kind)) - except: - raise ErrorDuringImport(path, sys.exc_info()) - file.close() + with open(path, 'r') as file: + try: + module = imp.load_module(name, file, path, (ext, 'r', kind)) + except: + raise ErrorDuringImport(path, sys.exc_info()) return module def safeimport(path, forceload=0, cache={}): @@ -1357,9 +1355,8 @@ """Page through text by invoking a program on a temporary file.""" import tempfile filename = tempfile.mktemp() - file = open(filename, 'w') - file.write(text) - file.close() + with open(filename, 'w') as file: + file.write(text) try: os.system(cmd + ' ' + filename) finally: @@ -1509,9 +1506,8 @@ try: object, name = resolve(thing, forceload) page = html.page(describe(object), html.document(object, name)) - file = open(name + '.html', 'w') - file.write(page) - file.close() + with open(name + '.html', 'w') as file: + file.write(page) print 'wrote', name + '.html' except (ImportError, ErrorDuringImport), value: print value Index: Lib/platform.py =================================================================== --- Lib/platform.py (revision 60326) +++ Lib/platform.py (working copy) @@ -144,35 +144,34 @@ # here to work around problems with Cygwin not being # able to open symlinks for reading executable = os.path.realpath(executable) - f = open(executable,'rb') - binary = f.read(chunksize) - pos = 0 - while 1: - m = _libc_search.search(binary,pos) - if not m: - binary = f.read(chunksize) - if not binary: - break - pos = 0 - continue - libcinit,glibc,glibcversion,so,threads,soversion = m.groups() - if libcinit and not lib: - lib = 'libc' - elif glibc: - if lib != 'glibc': - lib = 'glibc' - version = glibcversion - elif glibcversion > version: - version = glibcversion - elif so: - if lib != 'glibc': + with open(executable,'rb') as f: + binary = f.read(chunksize) + pos = 0 + while 1: + m = _libc_search.search(binary,pos) + if not m: + binary = f.read(chunksize) + if not binary: + break + pos = 0 + continue + libcinit,glibc,glibcversion,so,threads,soversion = m.groups() + if libcinit and not lib: lib = 'libc' - if soversion > version: - version = soversion - if threads and version[-len(threads):] != threads: - version = version + threads - pos = m.end() - f.close() + elif glibc: + if lib != 'glibc': + lib = 'glibc' + version = glibcversion + elif glibcversion > version: + version = glibcversion + elif so: + if lib != 'glibc': + lib = 'libc' + if soversion > version: + version = soversion + if threads and version[-len(threads):] != threads: + version = version + threads + pos = m.end() return lib,version def _dist_try_harder(distname,version,id): @@ -326,9 +325,8 @@ return _dist_try_harder(distname,version,id) # Read the first line - f = open('/etc/'+file, 'r') - firstline = f.readline() - f.close() + with open('/etc/'+file, 'r') as f: + firstline = f.readline() _distname, _version, _id = _parse_release_file(firstline) if _distname and full_distribution_name: Index: Lib/_LWPCookieJar.py =================================================================== --- Lib/_LWPCookieJar.py (revision 60326) +++ Lib/_LWPCookieJar.py (working copy) @@ -80,15 +80,12 @@ if self.filename is not None: filename = self.filename else: raise ValueError(MISSING_FILENAME_TEXT) - f = open(filename, "w") - try: + with open(filename, "w") as f: # There really isn't an LWP Cookies 2.0 format, but this indicates # that there is extra information in here (domain_dot and # port_spec) while still being compatible with libwww-perl, I hope. f.write("#LWP-Cookies-2.0\n") f.write(self.as_lwp_str(ignore_discard, ignore_expires)) - finally: - f.close() def _really_load(self, f, filename, ignore_discard, ignore_expires): magic = f.readline() Index: Lib/mailbox.py =================================================================== --- Lib/mailbox.py (revision 60326) +++ Lib/mailbox.py (working copy) @@ -313,14 +313,11 @@ def get_message(self, key): """Return a Message representation or raise a KeyError.""" subpath = self._lookup(key) - f = open(os.path.join(self._path, subpath), 'r') - try: + with open(os.path.join(self._path, subpath), 'r') as f: if self._factory: msg = self._factory(f) else: msg = MaildirMessage(f) - finally: - f.close() subdir, name = os.path.split(subpath) msg.set_subdir(subdir) if self.colon in name: @@ -330,11 +327,8 @@ def get_string(self, key): """Return a string representation or raise a KeyError.""" - f = open(os.path.join(self._path, self._lookup(key)), 'r') - try: + with open(os.path.join(self._path, self._lookup(key)), 'r') as f: return f.read() - finally: - f.close() def get_file(self, key): """Return a file-like representation or raise a KeyError.""" @@ -1019,8 +1013,7 @@ def get_sequences(self): """Return a name-to-key-list dictionary to define each sequence.""" results = {} - f = open(os.path.join(self._path, '.mh_sequences'), 'r') - try: + with open(os.path.join(self._path, '.mh_sequences'), 'r') as f: all_keys = set(self.keys()) for line in f: try: @@ -1039,8 +1032,6 @@ except ValueError: raise FormatError('Invalid sequence specification: %s' % line.rstrip()) - finally: - f.close() return results def set_sequences(self, sequences): Index: Lib/_MozillaCookieJar.py =================================================================== --- Lib/_MozillaCookieJar.py (revision 60326) +++ Lib/_MozillaCookieJar.py (working copy) @@ -115,8 +115,7 @@ if self.filename is not None: filename = self.filename else: raise ValueError(MISSING_FILENAME_TEXT) - f = open(filename, "w") - try: + with open(filename, "w") as f: f.write(self.header) now = time.time() for cookie in self: @@ -145,5 +144,3 @@ "\t".join([cookie.domain, initial_dot, cookie.path, secure, expires, name, value])+ "\n") - finally: - f.close() Index: Lib/zipfile.py =================================================================== --- Lib/zipfile.py (revision 60326) +++ Lib/zipfile.py (working copy) @@ -82,9 +82,8 @@ def is_zipfile(filename): """Quickly see if file is a ZIP file by checking the magic number.""" try: - fpin = open(filename, "rb") - endrec = _EndRecData(fpin) - fpin.close() + with open(filename, "rb") as fpin: + endrec = _EndRecData(fpin) if endrec: return True # file has correct magic number except IOError: @@ -924,28 +923,27 @@ self._writecheck(zinfo) self._didModify = True - fp = open(filename, "rb") - # Must overwrite CRC and sizes with correct data later - zinfo.CRC = CRC = 0 - zinfo.compress_size = compress_size = 0 - zinfo.file_size = file_size = 0 - self.fp.write(zinfo.FileHeader()) - if zinfo.compress_type == ZIP_DEFLATED: - cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, - zlib.DEFLATED, -15) - else: - cmpr = None - while 1: - buf = fp.read(1024 * 8) - if not buf: - break - file_size = file_size + len(buf) - CRC = binascii.crc32(buf, CRC) - if cmpr: - buf = cmpr.compress(buf) - compress_size = compress_size + len(buf) - self.fp.write(buf) - fp.close() + with open(filename, "rb") as fp: + # Must overwrite CRC and sizes with correct data later + zinfo.CRC = CRC = 0 + zinfo.compress_size = compress_size = 0 + zinfo.file_size = file_size = 0 + self.fp.write(zinfo.FileHeader()) + if zinfo.compress_type == ZIP_DEFLATED: + cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, + zlib.DEFLATED, -15) + else: + cmpr = None + while 1: + buf = fp.read(1024 * 8) + if not buf: + break + file_size = file_size + len(buf) + CRC = binascii.crc32(buf, CRC) + if cmpr: + buf = cmpr.compress(buf) + compress_size = compress_size + len(buf) + self.fp.write(buf) if cmpr: buf = cmpr.flush() compress_size = compress_size + len(buf) @@ -1240,9 +1238,8 @@ tgtdir = os.path.dirname(tgt) if not os.path.exists(tgtdir): os.makedirs(tgtdir) - fp = open(tgt, 'wb') - fp.write(zf.read(path)) - fp.close() + with open(tgt, 'wb') as fp: + fp.write(zf.read(path)) zf.close() elif args[0] == '-c':