本文共 1644 字,大约阅读时间需要 5 分钟。
实例1:一个项
with open(r'C:\Users\91135\Desktop\test.txt','r') as f: #该代码块执行结束后,自动关闭文件 print f.readlines()import timetime.sleep(3)print f.read() #文件已经关闭,执行该语句会出错结果:
['hello python\n', '\n', 'hello world\n', 'hello wahaha\n']
Traceback (most recent call last): File "E:\workspace\python day03\main\test.py", line 11, in <module> print f.read() #文件已经关闭,执行该语句会出错 ValueError: I/O operation on closed file实例2:多个项
with open(r'C:\Users\91135\Desktop\test.txt','r') as f,open(r'C:\Users\91135\Desktop\test1.txt','r') as f1: print f.readlines() print f1.readlines() #该语句块执行结束后,自动关闭文件
结果:
['hello python\n', '\n', 'hello world\n', 'hello wahaha\n']
['hello python\n', '\n', 'hello world\n', 'hello wahaha\n']实例3:异常处理
try: with open(r'C:\Users\91135\Desktop\wahaha.txt','r') as f:#假设文件wahaha.txt不存在 print f.readlines()except IOError,error: print error结果:
[Errno 2] No such file or directory: 'C:\\Users\\91135\\Desktop\\wahaha.txt'
实例4:读文件
#!/usr/bin/env python #coding:utf-8 def xreadlines(): pos=0 while True: #每次while循环,都在重新打开指定文件 with open(r'C:\Users\91135\Desktop\test.txt','r') as f: f.seek(pos) #找到上次关闭文件时,指针所在的位置 line=f.readline() if line: #若读取的字符串非空,执行该语句块 pos=f.tell() yield line #含有yield语句的函数称为生成器 else: return #若读取的字符串是空串,说明指针已经到达文件结尾,结束该函数 #当该with语句块执行结束时,自动关闭上述文件it=xreadlines()print itprint type(it)for line in xreadlines(): print line[:-1]结果:
<generator object xreadlines at 0x029D3260>
<type 'generator'> hello python hello world hello wahaha详细了解with as的前世今生,请参考:
转载地址:http://mjyai.baihongyu.com/