yidao620c / python3-cookbook

《Python Cookbook》 3rd Edition Translation
11.7k stars 2.97k forks source link

6.11节代码缩进问题 #231

Open fengyangfifa opened 6 years ago

fengyangfifa commented 6 years ago

from collections import namedtuple

Record = namedtuple('Record', ['kind','x','y'])

with open('data.p', 'rb') as f: records = (Record(*r) for r in read_records('<idd', f))

for r in records:
    print(r.kind, r.x, r.y)

这里应该把for循环写在with语句里面,否者会出现ValueError: read of closed file错误