@Scrazy
2016-02-15T08:28:59.000000Z
字数 576
阅读 859
python学习笔记
open()函数在python中读取文件使[TOC]用python内置的open()函数
>>> f = open('/home/mouse/test.txt', 'r')>>> print f.read()>>> f.close()
with()函数由于每次都要使用close()很是繁[TOC]琐,故引入with()函数
>>> with open('/path/to/file', 'r') as f... print(f.read())
可以省去每次使用close的麻烦。
read(size)方法对于小的文件可以直接使用read()如果太大的文件调用read(size)方法
readline()方法每次读取一行内容
暂时不研究二进制文件的读写问题,留个坑!!!
读写的方法都是一样的!
>>> f = open('/home/mouse/text.txt', 'w')# 'w'会覆盖原来的数据,换成'a'可以续写>>> f.write('I like Python')>>> f.close()#当然有 with()方法>>> with open('/home/mouse/test.txt', 'w') as f:... f.write('\n I Like Python')
open()函数切记要用close()with()函数是个好习惯