[python 笔记5]文件读写
2015-08-10 11:22
706 查看
1、定义
其中mode有:
2、读文件
1)读取整个文件
2)按字节数读取
3)按行读取
3、写文件
1)写入整个文件
2)按行写
4、关闭文件
在操作完成之后记得关闭文件
Close()
5、with语句
With语句可以打开文件(input.txt)并将其赋值给变量(test),之后就可以在代码块中对文件进行操作,在执行完之后文件会自动关闭。
在python2.5以后可以直接使用with语句,在2.5之前则需要添加以下语句
from __future__ import with_statement
open(filename[,mode[,buffering]])
其中mode有:
2、读文件
1)读取整个文件
test=open('input.txt','r') print test.read()
2)按字节数读取
test=open('input.txt','r') print test.read(10)
3)按行读取
test=open('input.txt','r') lines=test.readlines() print lines[1]
3、写文件
1)写入整个文件
test=open('output.txt','w') test.write('hello,python\nthis is my first test')
2)按行写
test=open('input.txt','r') lines=test.readlines() test.close() lines[1]='This is my second test' test=open('output.txt','w') test.writelines(lines) test.close()
4、关闭文件
在操作完成之后记得关闭文件
Close()
5、with语句
with open('input.txt','r') as test: print test.read()
With语句可以打开文件(input.txt)并将其赋值给变量(test),之后就可以在代码块中对文件进行操作,在执行完之后文件会自动关闭。
在python2.5以后可以直接使用with语句,在2.5之前则需要添加以下语句
from __future__ import with_statement
相关文章推荐
- python写的屏保程序
- Python开发入门与实战15-IIS部署
- Python内置类型——list
- win7下编译python源码
- 关于Windows系统下,Python读取文件的问题。
- win32下利用python操作printer
- Python Paste.deploy 笔记
- python 清理mail spool 下的小脚本
- 递归
- 你也可以有自己的天气预报啦!
- 0.python基本算法
- Solaris 10u11 安装python2.7.10
- python--获取网页图片
- python列表排序
- Python之Window环境搭建
- Python于*args 和**kwargs使用
- 零基础学python-1.6 错误的程序
- 零基础学python-1.6 错误的程序
- 正则匹配不包含某字符串(Python)
- 使用python执行复制时遇到的一点问题