Python 有关文件的操作示例

来源:互联网 发布:网络机顶盒apk 编辑:程序博客网 时间:2024/05/22 07:41

1、查找指定文件内的字符串个数

import refp = open('test.txt','r')count = 0for i in fp.readlines():list = re.findall("hello",i)if len(list)>0:count = count + len(list)print countfp.close()

2、替换文件

      读取一个文件,把其中指定的字符串替换为另一个,并保存到另一个文件,如下:

fp1 = open('test.txt','r')fp2 = open('test2.txt','w')for f in fp1.readlines():fp2.write(f.replace('hello','hehe'))fp1.close()fp2.close()

0 0
原创粉丝点击