使用with...as....语法打开一个文件
2017-01-03 22:58
274 查看
当使用open()打开一个不存在的文件时。最后通过finally关闭文件会报错
程序会报错:
出错啦:[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
解决办法为:
为了避免忘记关闭文件,可以使用with….as….
输出为:
出错了:not readable
感谢参考资料:
http://bbs.fishc.com/forum.php?mod=viewthread&tid=48291&extra=page%3D1%26filter%3Dtypeid%26typeid%3D398
# -*- 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
相关文章推荐
- sharepoint 2007 使用open with windows explorer的方式打开sharepoint 目录,然后批量复制文件,会导致被复制的文件信息被修改成当前用户和当前时间
- WinCE下使用C#来打开一个外部文件
- 重新想象 Windows 8 Store Apps (33) - 关联启动: 使用外部程序打开一个文件或uri, 关联指定的文件类型或协议
- Python中使用With打开多个文件
- Python基础——使用with结构打开多个文件
- 如何通过命令行或者使用代码打开一个apk文件
- python中使用with打开文件
- 如何在GNU/Linux操作系统中使用命令行xdg-open打开一个任意格式的文件
- 今天在Mac机器上使用了Flex Builder编辑了一个源代码文件,保存后使用vim命令去打开时发现系统自动在每一行的结尾添加了^M符号,其实^M在Linux/Unix中是非常常见的,也就是我们在Win中见过的/r回车符号。由于编辑软件的编码问题,某些IDE的编辑器在编辑完文件之后会自动加上这个^M符号。看起来对我们的源代码没有任何影响,其实并不然,当我们把源代码文件Check In到svn之类
- 问题: 在eclipse里使用ctr+shift+t打开一个类的时候,出现错误:Class file name must end with .class
- 请问使用C++如何打开一个文件
- Notepad++打开as文件时使用as3的语法高亮
- Linux 文件系统剖析: 使用 /proc 文件系统来访问 Linux 内核的内容 这个虚拟文件系统在内核空间和用户空间之间打开了一个通信窗口
- 在使用O_APPEND 标志并以写打开一个已存在的文件,然后用lseek函数将偏移置于开头,在写入数据,写入的数据会显示在那个位置呢???
- Notepad++打开as文件时使用as3的语法高亮
- 如何使用java程序打开一个文件?
- 重新想象 Windows 8 Store Apps (33) - 关联启动: 使用外部程序打开一个文件或uri, 关联指定的文件类型或协议
- Python中使用with语句同时打开多个文件
- Java7中使用try-with-resource语法 实现两种复制文件方法
- delphi 打开文件夹并定位到一个文件(使用ShellExecute时加一个select参数,原来这么简单!)