qileilove

blog已经转移至github,大家请访问 http://qaseven.github.io/

python文件读写

同样是《python基础教程(第二版)》的内容,只是后面内容学起来,相比前面会比较有趣,也更加实用,所以,将“基础”改为“进阶”。

python 电子书分享地址:http://yunpan.cn/Q2U87uGrNiTA3

 

本节讲文件的操作

-------------------------------

 

打开文件

 

open函数用来打开文件,语法如下:

open(name[, mode[,buffering]])

open函数使用一个文件名作为唯一的强制参数,然后返回一个文件对象。假设我要打开我硬盘(I/python/test.txt) 文件,可以用下面方法:

>>> f = open(r'i:\python\test.txt')

 

open函数中模式参数的常用值

 

 

基本文件方法

 

打开文件是第一步,下面就需要对文件进行读或写,可以write 和 read方法进行读或写。

复制代码
#写入文件内容 >>> f = open('test.txt','w') >>> f.write('hello,') >>> f.write('world!') >>> f.close()  # 读取文件内容 >>> f = open('test.txt','r') >>> f.read(4)   #读取前4个字符 'hell' >>> f.read()   #读取剩余的所有字符 'o,world!'
复制代码

 

关闭文件

  应该牢记使用close方法关闭文件。尽管一个文件对象在退出程序后会自动关闭,但关闭文件是没什么害处的,可以避免在某些操作系统或设置中进行无用的修改,这样做也会避免用完系统中打开文件的配额。

 

 

使用基本文件方法

 

假如test.txt文件包含如下内容:

-----------------------------

Welcome to this file

There is nothing here except

This stupid haiku

-----------------------------

下面是基本读文件的方法:

复制代码
# read(n) 指定参数 >>> f = open(r'I:\python\test.txt') >>> f.read(7) 'Welcome' >>> f.read(4) ' to ' >>> f.close()  # read() 不指定参数 >>> f = open(r'I:\python\test.txt') >>> print f.read() Welcome to this file There is nothing here except This stupid haiku >>> f.close()  # readline()  >>> f = open(r'I:\python\test.txt') >>> for i in range(3):     print str(i) + ':' + f.readline()       0:Welcome to this file  1:There is nothing here except  2:This stupid haiku >>> f.close()  #readlines() >>> import pprint >>> pprint.pprint(open(r'I:\python\test.txt').readlines()) ['Welcome to this file\n',  'There is nothing here except\n',  'This stupid haiku']
复制代码

readline返回一行的字符串, readlines返回包含文件所有内容的字符串列表每个元素是一行的字符串

pprint 模块的pprint方法将内容分成每个小项单行显示。

 

下面是写文件的基本方法:

>>> f = open(r'I:\python\test.txt','w')  #默认是读文件,可以不加‘r’,写文件一定要加’w’ >>> f.write('this\nis no \nhaiku') >>> f.close()

 

>>> f = open(r'I:\python\test.txt') >>> lines = f.readlines() >>> lines[1] = "isn't a\n" >>> f = open(r'I:\python\test.txt','w') >>> f.writelines(lines) >>> f.close()

 

 

对文件内容进行迭代

 

1、接字节处理

最常见的对文件内容进行迭代的方法是while循环中使用read方法。例如,对每个字符进行循环,可以用下面方法实现:

f = open(filename) char = f.read(1) while char:     process(char)     char = f.read(1) f.close()

read方法返回的字符串会包含一个字符,直到文件末尾,read返回一个空的字符串,char将变为假。

可以看到,char = f.read(1) 被重复地使用,代码重复通过被认为是一件坏事,看看下面的方法:

复制代码
f = open(filename)  while True:     char = f.read(1)     if not char: break     process(char) f.close()
复制代码

这里break语句被频繁的使用(这样会让代码比较难懂),尽管如此,但它仍然要比前面的方法好。

 

2、读取所有内容

如果文件不是很大,那么可以使用不带参数的read方法一次读取整个文件,或者使用readlines方法。

复制代码
#用read迭代每个字符 f = open(filename) for char in f.read():     process(char) f.close() 
#用readlines迭代行: f = open(filename) for line in f.readlines(): process(line) f.close()
复制代码

 

3、用fileinput 来进行迭代

fileinput模块包含了打开文件的函数,,只需要传一个文件名给它

import fileinput for line in fileinput.input(filename):     process(line)

 

4、文件迭代器

好吧!这是python2.2之后才有的方法,如果它一开始就有,上面的方法也许就不存在了。文件对象是可以迭代的,这就意味着可以直接在for循环中对他们进行迭代

f = open(filename) for line in f:     process(line) f.close()

 

 

再来看下面例子:

复制代码
>>> f = open(r'I:\python\test.txt','w') >>> f.write('First line\n') >>> f.write('Second line\n') >>> f.write('Third line\n') >>> f.close() >>> lines = list(open(r'I:\python\test.txt')) >>> lines ['First line\n', 'Second line\n', 'Third line\n'] >>> first,second,third = open(r'I:\python\test.txt') >>> first 'First line\n' >>> second 'Second line\n' >>> third 'Third line\n'
复制代码

在这个例子中:

 

  •  使用序列来对一个打开的文件进行解包操作,把每行都放入一个单独的变理中,这么做是很有实用性的,因为一般不知道文件中有多少行,但它演示的文件的“迭代性”。
  •  在写文件后一定要关闭文件,这样才能确保数据被更新到硬盘。

 

posted on 2014-02-20 11:46 顺其自然EVO 阅读(213) 评论(0)  编辑  收藏 所属分类: python


只有注册用户登录后才能发表评论。


网站导航:
 
<2024年3月>
252627282912
3456789
10111213141516
17181920212223
24252627282930
31123456

导航

统计

常用链接

留言簿(55)

随笔分类

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜