用Python实现分割合并文件的方法
小编给大家分享一下用Python实现分割合并文件的方法,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!
在平常的生活中,我们会遇到下面这样的情况:
你下载了一个比较大型的游戏(假设有10G),现在想跟你的同学一起玩,你需要把这个游戏拷贝给他。
然后现在有一个问题是文件太大(我们不考虑你有移动硬盘什么的情况),假设现在只有一个2G或4G的优盘,该怎么办呢?
有很多方法,例如winrar压缩的时候分成很多小卷,这里不累述。
在学习python之后,我们自己就可以解决这个问题啦。
我们可以自己写一个脚本去分割合并文件,将文件分割成适合优盘大小的小文件,再拷贝,然后再合并。
importsys,oskilobytes=1024megabytes=kilobytes*1000chunksize=int(200*megabytes)#defaultchunksizedefsplit(fromfile,todir,chunksize=chunksize):ifnotos.path.exists(todir):#checkwhethertodirexistsornotos.mkdir(todir)else:forfnameinos.listdir(todir):os.remove(os.path.join(todir,fname))partnum=0inputfile=open(fromfile,'rb')#openthefromfilewhileTrue:chunk=inputfile.read(chunksize)ifnotchunk:#checkthechunkisemptybreakpartnum+=1filename=os.path.join(todir,('part%04d'%partnum))fileobj=open(filename,'wb')#makepartfilefileobj.write(chunk)#writedataintopartfilefileobj.close()returnpartnumif__name__=='__main__':fromfile=input('Filetobesplit?')todir=input('Directorytostorepartfiles?')chunksize=int(input('Chunksizetobesplit?'))absfrom,absto=map(os.path.abspath,[fromfile,todir])print('Splitting',absfrom,'to',absto,'by',chunksize)try:parts=split(fromfile,todir,chunksize)except:print('Errorduringsplit:')print(sys.exc_info()[0],sys.exc_info()[1])else:print('splitfinished:',parts,'partsarein',absto)
下面是脚本运行的例子:
我们在F有一个X—MEN1.rar文件,1.26G大小,我们现在把它分割成400000000bit(大约380M)的文件。
Python3.4.1(v3.4.1:c0e311e010fc,May182014,10:45:13)[MSCv.160064bit(AMD64)]onwin32Type"copyright","credits"or"license()"formoreinformation.>>>================================RESTART================================>>>Filetobesplit?F:\X-MEN1.rarDirectorytostorepartfiles?F:\splitChunksizetobesplit?400000000SplittingF:\X-MEN1.rartoF:\splitby400000000splitfinished:4partsareinF:\split>>>
这是分割后的文件:
下面是文件合并脚本:
importsys,osdefjoinfile(fromdir,filename,todir):ifnotos.path.exists(todir):os.mkdir(todir)ifnotos.path.exists(fromdir):print('Wrongdirectory')outfile=open(os.path.join(todir,filename),'wb')files=os.listdir(fromdir)#listallthepartfilesinthedirectoryfiles.sort()#sortpartfilestoreadinorderforfileinfiles:filepath=os.path.join(fromdir,file)infile=open(filepath,'rb')data=infile.read()outfile.write(data)infile.close()outfile.close()if__name__=='__main__':fromdir=input('Directorycontainingpartfiles?')filename=input('Nameoffiletoberecreated?')todir=input('Directorytostorerecreatedfile?')try:joinfile(fromdir,filename,todir)except:print('Errorjoiningfiles:')print(sys.exc_info()[0],sys.exc_info()[1])
运行合并脚本,将上面分割脚本分割的文件重组:
Python3.4.1(v3.4.1:c0e311e010fc,May182014,10:45:13)[MSCv.160064bit(AMD64)]onwin32Type"copyright","credits"or"license()"formoreinformation.>>>================================RESTART================================>>>Directorycontainingpartfiles?F:\splitNameoffiletoberecreated?xman1.rarDirectorytostorerecreatedfile?F:\>>>
运行之后可以看到F盘下生成了重组的xman.rar。
看完了这篇文章,相信你对用Python实现分割合并文件的方法有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。