python切分apache日志文件

来源:互联网 发布:k均值聚类算法步骤 编辑:程序博客网 时间:2024/05/16 08:01
1、使用python将文件切分为两个文件

#!/usr/bin/env python
# -*- coding:UTF-8 -*-
import os,sys
N = 0.8
lines = open('access_2013.log','r').readlines()
#读取文件
lines_for_b = int(len(lines)*N)
#计算行数
open('a.txt','w').write(''.join(lines[:lines_for_b]))
#生成第一个文件
open('b.txt','w').write(''.join(lines[lines_for_b:]))
#生成第二个文件

2、将文件切割多个文件,每个文件按照30M切分
#!/usr/bin/env python
def split(filename,size):
    fp = open(filename, 'rb')
    i = 0
    n = 0
    temp = open(filename+'.part'+str(i),'wb')
    buf = fp.read(1024)
    while(True):
        temp.write(buf)
        buf=fp.read(1024)
        if(buf == ''):
            print filename+'.part'+str(i)+';'
            temp.close
            fp.close()
            return
        n+=1
        if(n == size):
            n = 0
            print filename+'.part'+str(i)+';'
            i += 1
            temp.close()
            temp = open(filename+'.part'+str(i),'wb')

if __name__=='__main__':
    name = raw_input('input filename:')
    split(name,30720)    #按照30M切分
0 0