Index: Doc/library/collections.rst =================================================================== --- Doc/library/collections.rst (revision 86561) +++ Doc/library/collections.rst (working copy) @@ -52,7 +52,8 @@ >>> # Find the ten most common words in Hamlet >>> import re - >>> words = re.findall('\w+', open('hamlet.txt').read().lower()) + >>> with open('hamlet.txt') as f: + ... words = re.findall(r'\w+', f.read().lower()) >>> Counter(words).most_common(10) [('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631), ('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)] @@ -398,7 +399,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:: @@ -650,8 +652,9 @@ EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade') import csv - for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))): - print(emp.name, emp.title) + with open('employees.csv', 'rb') as f: + for emp in map(EmployeeRecord._make, csv.reader(f)): + print(emp.name, emp.title) import sqlite3 conn = sqlite3.connect('/companydata')