博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python with as 简单使用
阅读量:4171 次
发布时间:2019-05-26

本文共 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/

你可能感兴趣的文章
linux系统管理—第五章Linux-bashshell
查看>>
PostgreSQL数据库管理 第二章体系结构
查看>>
PostgreSQL数据库管理 第三章实例管理与管理工具
查看>>
PostgreSQL数据库管理第七章流复制
查看>>
PostgreSQL数据库管理第十章Repmgr
查看>>
PostgreSQL数据库管理 第八章日常运维
查看>>
MySQL数据库管理-体系结构
查看>>
软考UML
查看>>
信息系统的生命周期各阶段及说明
查看>>
Ubuntulinux离线安装ClamTk杀毒软件步骤和使用方法
查看>>
摆脱贫穷2021V1
查看>>
Android.Could not find *.apk
查看>>
JNI
查看>>
Android基于TranslateAnimation的动画动态菜单
查看>>
android NDK中的GCC编译器
查看>>
Android NOtification 使用
查看>>
Android的SharedPreferences保存与删除数据简单实例
查看>>
android 如何从sqlite读取数据到spinner下拉中显示
查看>>
Android实现开机自动运行程序
查看>>
最近几天搭建MySql且连接问题总结
查看>>