Python学习 之 文件

1、文件读写

python进行文件读写的函数是open或file

file_handler=open(filename,,mode)

(1)打开并读取文件

方式一:open()

fo=open('/root/test.txt')
fo   #查看fo信息
fo.read()   #读取文件内容
fo.close()   #关闭文件

 方式二:file()

fo=file('/root/test.txt')
fo.read()   #读取文件内容
fo.close() #关闭文件

(2)文件写入

 打开文件时的读写模式如下表所示:

代码一:

fnew=open('/root/new.txt','r+')
fnew.read()
fnew.write("new contents")
fnew.close()

代码二:

fnew=open('/root/new.txt','r+')
fnew.write("new contents")
fnew.close()

代码一中在文件末尾追加写入的内容,代码二是覆盖以前的内容,区别在于代码一多了fnew.read()

2、文件对象方法

(1)FileObject.close()

(2)String=FileObject.readline([size])

(3)List=FileObject.readlines([size])

(4)String=FileObject.read([size])

  读取文件前size个字符

(5)FileObject.next()

  返回当前行,并将文件指针指到下一行

(6)FileObject.write(string)

(7)FileObject.writelines(List)

  效率比write高,速度更快,少量写入可以使用write

(8)FileObject.seek(偏移量,选项)

  选项=0,表示将文件指针指向从文件头部到“偏移量”字节处

  选项=1,表示将文件指针指向从文件的当前位置,向后移动“偏移量”字节

  选项=2,表示将文件指针指向从文件的尾部,向前移动“偏移量”字节

(9)FileObject.flush()

3、文件操作示例

(1)统计文件中hello的个数

import re
fp=file("a.t","r")
count=0
for s in fp.readlines():
    li=re.findall("hello",s)
    if len(li)>0:
        count+=len(li)
print "Search "+count+" hello"
fp.close()

(2)把a.t中的hello替换为csvt,并把结果保存到a2.t中

fp1=file("a.t","r")
fp2=file("a2.t","w")
for s in f1.readlines():
    fp2.write(s.replace("hello","csvt"))
fp1.close()
fp2.close()

(3)把a.t中的hello替换为csvt,并把结果保存到原文件中

fp1=file("a.t","r+")
for s in fp1.readlines():
        fp1.writeline(s.replace("hello","csvt"))
fp1.close()

4、文件操作的其他应用

目录分析器

杀毒软件

系统垃圾清理工具

posted @ 2015-06-23 20:07  sunflower627  阅读(268)  评论(0编辑  收藏  举报