python中使用with打开文件
2013-07-21 16:11
375 查看
file object拥有__enter__和__exit__方法,前者仅仅是返回object自己,而后者则关闭这个文件:
>>> f = open("x.txt")
>>> f
<open file 'x.txt', mode 'r' at 0x00AE82F0>
>>> f.__enter__()
<open file 'x.txt', mode 'r' at 0x00AE82F0>
>>> f.read(1)
'X'
>>> f.__exit__(None, None, None)
>>> f.read(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file
所以打开文件读取文件中内容可以简单写成:
可以看到到ptint f 这一行时文件已经被关闭了
<closed file 'test.txt', mode 'r' at 0x02055230>
>>> f = open("x.txt")
>>> f
<open file 'x.txt', mode 'r' at 0x00AE82F0>
>>> f.__enter__()
<open file 'x.txt', mode 'r' at 0x00AE82F0>
>>> f.read(1)
'X'
>>> f.__exit__(None, None, None)
>>> f.read(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file
所以打开文件读取文件中内容可以简单写成:
if __name__ == "__main__": with open("test.txt") as f: lines = f.readlines() print f
可以看到到ptint f 这一行时文件已经被关闭了
<closed file 'test.txt', mode 'r' at 0x02055230>
相关文章推荐
- Python基础——使用with结构打开多个文件
- Python基础——使用with结构打开多个文件
- [问答]Python 打开多个文件怎么使用 "with open"
- Python中使用with语句同时打开多个文件
- Python中使用With打开多个文件
- python基础-打开模式、seek、修改文件、with上下文管理、truncate
- 使用python 打开文件并做匹配处理
- python使用open直接打开一个不确定存在的文件
- 文件操作之增删改查3---文件的修改,f.replace(),在linux里的一些应用sed,with语句方法来打开一个或多个文件避免忘记关闭,python一行写的太长,怎么编写多行的规范
- python 使用 urllib.urlretrieve()下载网络图片,在本地打开提示文件损坏无法打开
- Python:打开文件读取每一行(使用with as)
- C/C++/Python等 使用二进制模式打开文件与不使用二进制模式的区别
- [Python入门]使用open打开文件一直为空
- python使用wxPython打开并播放wav文件的方法
- python使用open打开文件中文乱码
- python在提示符下使用open打开文件失败原因
- 解决python使用open打开文件中文乱码的问题
- Python--使用json.dumps 将 json 格式的数据写到文件里--with open as f
- sharepoint 2007 使用open with windows explorer的方式打开sharepoint 目录,然后批量复制文件,会导致被复制的文件信息被修改成当前用户和当前时间
- 使用with...as....语法打开一个文件