python_41_with语句
#为了避免打开文件后忘记关闭,可以通过管理上下文,即:with open('log','r') as f: # 如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。 with open('yesterday','r',encoding='utf-8') as f: for line in f:#只是个例子 print(line) #注:python规范,一行代码不要超过80个字符。 #在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:with open('log1') as obj1, open('log2') as obj2: with open('yesterday','r',encoding='utf-8') as f,\ open('yyy','r',encoding='utf-8') as f1: for line in f:#只是个例子 print(line) with open('mmm','w',encoding='utf-8') as f: f.write('aaaa')