码迷,mamicode.com
首页 > 编程语言 > 详细

[python 笔记5]文件读写

时间:2015-08-10 12:01:10      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:python   文件读写   io   

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


版权声明:本文为博主原创文章,未经博主允许不得转载。

[python 笔记5]文件读写

标签:python   文件读写   io   

原文地址:http://blog.csdn.net/er_plough/article/details/47396103

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!