日志文件分割器

本文介绍了一个简单的文件分割工具,能够将大型文件分割成指定大小的小文件,便于网络传输或存储管理。用户可以自定义分割后的文件大小及存放目录。
import sys,os,re
kilobytes = 1024
megabytes = kilobytes*1024
chunksize = int(10*megabytes)
def split(fromfile,todir,chunksize):
print(fromfile,todir,chunksize)
if not os.path.exists(todir):#check todir exsits or not
os.mkdir(todir)
else:
for fname in os.listdir(todir):
os.remove(os.path.join(todir,fname))
index=0
inputfile = open(fromfile,'rb')#
while True:
chunk = inputfile.read(chunksize)
if not chunk:             #check the chunk is empty
break
index += 1
filename = os.path.join(todir,('part'+str(index)+"."+fromfile.split('.')[-1]))
fw = open(filename,'w')
fw.write(str(chunk))         #write data into partfile
fw.close()
inputfile.close()

return index


if __name__=='__main__':
fromfile  = input('File to be split?'+"\n input:")
todir     = input('Directory to store part files?'+"\n input:")
n = int(input('Chunksize to be split mb?'+"\n input:"))
chunksize = int(n*megabytes)
absfrom,absto = map(os.path.abspath,[fromfile,todir])
print('Splitting',absfrom,'to',absto,'by',chunksize)
try:
index = split(fromfile,todir,chunksize)
except:
print('Error during split:')
print(sys.exc_info()[0],sys.exc_info()[1])
else:
print('split finished:',index,'parts are in',absto)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值