python with as 简单使用

实例1:一个项

with open(r'C:\Users\91135\Desktop\test.txt','r') as f:
    #该代码块执行结束后,自动关闭文件
    print f.readlines()

import time
time.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 it
print type(it)
for line in xreadlines():
    print line[:-1]
结果:

<generator object xreadlines at 0x029D3260>
<type 'generator'>
hello python


hello world
hello wahaha

详细了解with as的前世今生,请参考:理解Python中的with…as…语法





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值