Index: tutorial/stdlib2.rst =================================================================== --- tutorial/stdlib2.rst (révision 86660) +++ tutorial/stdlib2.rst (copie de travail) @@ -141,7 +141,9 @@ import struct - data = open('myfile.zip', 'rb').read() + with open('myfile.zip', 'rb') as f: + data = f.read() + start = 0 for i in range(3): # show the first 3 file headers start += 14 Index: library/logging.rst =================================================================== --- library/logging.rst (révision 86660) +++ library/logging.rst (copie de travail) @@ -4000,7 +4000,8 @@ #!/usr/bin/env python import socket, sys, struct - data_to_send = open(sys.argv[1], "r").read() + with open(sys.argv[1], 'rb') as f: + data_to_send = f.read() HOST = 'localhost' PORT = 9999 Index: library/cmd.rst =================================================================== --- library/cmd.rst (révision 86660) +++ library/cmd.rst (copie de travail) @@ -283,8 +283,8 @@ def do_playback(self, arg): 'Playback commands from a file: PLAYBACK rose.cmd' self.close() - cmds = open(arg).read().splitlines() - self.cmdqueue.extend(cmds) + with open(arg) as f: + self.cmdqueue.extend(f.read().splitlines()) def precmd(self, line): line = line.lower() if self.file and 'playback' not in line: Index: library/atexit.rst =================================================================== --- library/atexit.rst (révision 86660) +++ library/atexit.rst (copie de travail) @@ -66,17 +66,22 @@ automatically when the program terminates without relying on the application making an explicit call into this module at termination. :: + infile = open("/tmp/counter") try: - _count = int(open("/tmp/counter").read()) + _count = int(infile.read()) except IOError: _count = 0 + finally: + infile.close() + def incrcounter(n): global _count _count = _count + n def savecounter(): - open("/tmp/counter", "w").write("%d" % _count) + with open("/tmp/counter", "w") as outfile: + outfile.write("%d" % _count) import atexit atexit.register(savecounter) Index: library/collections.rst =================================================================== --- library/collections.rst (révision 86660) +++ library/collections.rst (copie de travail) @@ -398,7 +398,8 @@ def tail(filename, n=10): 'Return the last n lines of a file' - return deque(open(filename), n) + with open(filename) as f: + return deque(f, n) Another approach to using deques is to maintain a sequence of recently added elements by appending to the right and popping to the left::