Skip to content

Instantly share code, notes, and snippets.

@borgle
Last active August 29, 2015 14:05
Show Gist options
  • Save borgle/ff641a1c71d5d018d031 to your computer and use it in GitHub Desktop.
Save borgle/ff641a1c71d5d018d031 to your computer and use it in GitHub Desktop.
一个简单的按指定行数分割文件python代码,有时候分析系统记录的日志非常方便
#!/usr/bin/env python
#coding=utf-8
import time,re,os,sys
def module_path():
""" This will get us the program's directory,
even if we are frozen using py2exe"""
if hasattr(sys, "frozen"):
return os.path.dirname(sys.executable)
return os.path.dirname(__file__)
def fenge(folder,filename):
APPLICATION_PATH = module_path()
outfolder = os.path.join(APPLICATION_PATH, folder)
filepath = os.path.join(outfolder,filename)
i,j,l = 1,0,0
f = file(filepath,'r')
s = f.readline()
of = os.path.join(outfolder, '%s.txt' % i)
w = file(of,'w');
while s:
j,l = j + 1,l + 1
sys.stdout.write('\r')
print '正在处理 %s\%s 第 %s 行.' % (folder,filename,j),
if j % 38000 == 0:
sys.stdout.write('\r')
print '文件 %s, 共 %s 行.' % (of,l)
w.close()
i,l = i + 1,0
of = os.path.join(outfolder, '%s.txt' % i)
w = file(of, 'w')
w.write(s)
s = f.readline()
w.write(s)
w.close()
sys.stdout.write('\r')
print '文件 %s, 共 %s 行.' % (of, l+1)
f.close()
if __name__ == "__main__":
fenge('bbb','bb.txt')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment