Use with statement where it improves the documentation (closes #10461)

This commit is contained in:
Éric Araujo 2011-03-11 17:42:48 +01:00
parent 17b880a5d6
commit a3dd56b6cf
5 changed files with 16 additions and 8 deletions

View File

@ -61,17 +61,22 @@ from a file when it is imported and save the counter's updated value
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)

View File

@ -282,8 +282,8 @@ immediate playback::
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:

View File

@ -512,7 +512,8 @@ in Unix::
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::

View File

@ -750,8 +750,8 @@ It is also contained in the Python source distribution, as
# we're passing these as arguments to the diff function
fromdate = time.ctime(os.stat(fromfile).st_mtime)
todate = time.ctime(os.stat(tofile).st_mtime)
fromlines = open(fromfile, 'U').readlines()
tolines = open(tofile, 'U').readlines()
with open(fromlines) as fromf, open(tofile) as tof:
fromlines, tolines = list(fromf), list(tof)
if options.u:
diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile,

View File

@ -141,7 +141,9 @@ standard size and in little-endian byte order::
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