您的位置:首页 > 编程语言 > Python开发

[python 笔记5]文件读写

2015-08-10 11:22 706 查看
1、定义

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: