python文件读写

为了熟悉python的文件读写,写了一个小程序

#coding=utf-8
import os
import sys
import re

f1 = open('xxx.log','r')
f2 = open('temp.txt','w')
lines = f1.readlines()
num = 0
for line in lines:
    if line[0]=='2' and line[1]=='0' and line[2]=='1' and line[4]=='-':
       f2.write('\n')
       num = num + 1
    line = line.strip('\n')
    f2.write(line)
print "total num:"
print num
f1.close()
f2.close()
f1=open('temp.txt','r')
f2=open('result.txt','w')
lines = f1.readlines()
for line in lines:
    m=re.search('password',line)       #匹配password的行
    if m:
        strlist=line.split('\t')
        str=strlist[5] + '\n'
        f2.write(str)
f1.close()
f2.close()
os.remove('temp.txt')

readlines()读文件将文件按行读取到一个列表中,

line = line.strip('\n')表示读取的每行是包括行末尾的换行符的,如果需要去掉换行符,就要用strip()
常见的字符串处理见http://www.cnblogs.com/huangcong/archive/2011/08/29/2158268.html

re模块的详细使用见http://wenku.baidu.com/view/ea543160caaedd3383c4d3d0.html

posted @ 2012-10-30 14:09  聂风  阅读(243)  评论(0编辑  收藏  举报