背景
你是否有遇到过文本文档太大无法打开的情况?比如说压测了好几天,生成了一个十几 G 的日志文件。
下面这个脚本可以帮助你将一个大文件分解成一个小文件。
假设文件名位:splitfile.py
使用方法位:python splitfile.py log 20
该文件将会将 log 文件拆分成 log.0 log.1 log.2 ... log.19 等 20 个文件
源码
import os
import sys
if len( sys.argv ) < 3:
print( "Please specify file and how many you want split" );
print( "python %s log 10"%(sys.argv[0]) );
sys.exit(-1)
logfile = sys.argv[1]
cutnbs = int(sys.argv[2])
if os.path.isfile( logfile ) == False:
print( "%s is not file"%( logfile ) );
exit(-1)
f_stat = os.stat( logfile )
print(f_stat)
f_basename = os.path.basename( logfile )
print(f_basename)
f_size = f_stat.st_size
sub_f_size = f_size / cutnbs + cutnbs
# print( f_size )
infd = open( logfile, 'rb' );
for i in range( cutnbs ):
size_count = 0
o_filename = "./%s.%d"%( f_basename, i )
print( "out filename: %s"%( o_filename ) )
print( "start dumpL %s"%( o_filename ) )
if os.path.isfile( o_filename ):
os.remove( o_filename )
o_fd = open( o_filename, 'xb' )
while size_count < sub_f_size:
line = infd.read( 1024*1024 )
if len(line) == 0:
break
o_fd.write( line )
size_count += len( line )
o_fd.close()
infd.close()
exit(0)
标签:python,filename,sys,拆解,文本文件,print,logfile,os,size
From: https://www.cnblogs.com/mojies/p/17957046