使用with...as....语法打开一个文件
来源:互联网 发布:c语言 新建文件追加 编辑:程序博客网 时间:2024/06/13 21:25
当使用open()打开一个不存在的文件时。最后通过finally关闭文件会报错
# -*- coding: utf-8 -*-try: f=open("dataaaa.txt","w") for each_line in f: print (each_line)except OSError as reason: print("出错了:"+str(reason))finally: f.close()
程序会报错:
出错啦:[Errno 2] No such file or directory: ‘dataaaa.txt’
Traceback (most recent call last):
File “E:/Python Program/test.py”, line 19, in
f.close()
NameError: name ‘f’ is not defined
解决办法为:
# -*- coding: utf-8 -*-try: f=open("dataaaa.txt","w") for each_line in f: print (each_line)except OSError as reason: print("出错了:"+str(reason))finally: if 'f' in locals(): # 如果文件对象变量存在当前局部变量符号表的话,说明打开成功 f.close()
为了避免忘记关闭文件,可以使用with….as….
# -*- coding: utf-8 -*-try: with open("dataaaa.txt","w") as f: for each_line in f: print (each_line)except OSError as reason: print("出错了:"+str(reason))
输出为:
出错了:not readable
感谢参考资料:
http://bbs.fishc.com/forum.php?mod=viewthread&tid=48291&extra=page%3D1%26filter%3Dtypeid%26typeid%3D398
0 0
- 使用with...as....语法打开一个文件
- Python:打开文件读取每一行(使用with as)
- SQL中WITH AS语法的使用
- Notepad++打开as文件时使用as3的语法高亮
- SQL --- with as 语法
- ORACLE WITH AS 语法
- oracle with as 语法
- python with as语法
- oracle with as 语法
- DB2 with as 语法
- python with as语法
- python with..as 语法
- python with as语法
- 读取文件、OS模块、异常处理、with as语法
- SQL中with as语法的介绍和使用
- Python中的with...as语法
- python with...as语法理解
- python中使用with打开文件
- 串口中怎样接收一个完整数据包的解析
- SQL 数据优化索引建suo避免全表扫描
- final, finally, finalize的区别
- 手把手教你在Photoshop中使用曲线工具
- Asm Shader Reference --- Shader Model 3.0 part
- 使用with...as....语法打开一个文件
- mac开发中,怎么用iTunes安装spa包
- Error:Execution failed for task ':zebradrive_sdk:clean'. > Unable to delete directory: D:\AndroidStu
- javascript的值与类型
- 疯狂JAVA讲义学习笔记4——面向对象1
- react native 定位
- 【Maven】添加ueditor到maven本地仓库
- 单片机上下拉电阻
- 【PL/SQL调试】SQL*Plus 或者 PL/SQL Developer查看存储过程编译错误