Python实现分割文件及合并文件的方法
本文实例讲述了Python实现分割文件及合并文件的方法。分享给大家供大家参考。具体如下:
分割文件split.py如下:
#!/usr/bin/python
##########################################################################
#splitafileintoasetofparts;join.pyputsthembacktogether;
#thisisacustomizableversionofthestandardunixsplitcommand-line
#utility;becauseitiswritteninPython,italsoworksonWindowsand
#canbeeasilymodified;becauseitexportsafunction,itslogiccan
#alsobeimportedandreusedinotherapplications;
##########################################################################
importsys,os
kilobytes=1024
megabytes=kilobytes*1000
chunksize=int(1.4*megabytes)#default:roughlyafloppy
defsplit(fromfile,todir,chunksize=chunksize):
ifnotos.path.exists(todir):#callerhandleserrors
os.mkdir(todir)#makedir,read/writeparts
else:
forfnameinos.listdir(todir):#deleteanyexistingfiles
os.remove(os.path.join(todir,fname))
partnum=0
input=open(fromfile,'rb')#usebinarymodeonWindows
while1:#eof=emptystringfromread
chunk=input.read(chunksize)#getnextpart<=chunksize
ifnotchunk:break
partnum=partnum+1
filename=os.path.join(todir,('part%04d'%partnum))
fileobj=open(filename,'wb')
fileobj.write(chunk)
fileobj.close()#orsimplyopen().write()
input.close()
assertpartnum<=9999#joinsortfailsif5digits
returnpartnum
if__name__=='__main__':
iflen(sys.argv)==2andsys.argv[1]=='-help':
print'Use:split.py[file-to-splittarget-dir[chunksize]]'
else:
iflen(sys.argv)<3:
interactive=1
fromfile=raw_input('Filetobesplit?')#inputifclicked
todir=raw_input('Directorytostorepartfiles?')
else:
interactive=0
fromfile,todir=sys.argv[1:3]#argsincmdline
iflen(sys.argv)==4:chunksize=int(sys.argv[3])
absfrom,absto=map(os.path.abspath,[fromfile,todir])
print'Splitting',absfrom,'to',absto,'by',chunksize
try:
parts=split(fromfile,todir,chunksize)
except:
print'Errorduringsplit:'
printsys.exc_info()[0],sys.exc_info()[1]
else:
print'Splitfinished:',parts,'partsarein',absto
ifinteractive:raw_input('PressEnterkey')#pauseifclicked
合并文件join_file.py如下:
#!/usr/bin/python
##########################################################################
#joinallpartfilesinadircreatedbysplit.py,torecreatefile.
#Thisisroughlylikea'catfromdir/*>tofile'commandonunix,butis
#moreportableandconfigurable,andexportsthejoinoperationasa
#reusablefunction.Reliesonsortorderoffilenames:mustbesame
#length.Couldextendsplit/jointopopupTkinterfileselectors.
##########################################################################
importos,sys
readsize=1024
defjoin(fromdir,tofile):
output=open(tofile,'wb')
parts=os.listdir(fromdir)
parts.sort()
forfilenameinparts:
filepath=os.path.join(fromdir,filename)
fileobj=open(filepath,'rb')
while1:
filebytes=fileobj.read(readsize)
ifnotfilebytes:break
output.write(filebytes)
fileobj.close()
output.close()
if__name__=='__main__':
iflen(sys.argv)==2andsys.argv[1]=='-help':
print'Use:join.py[from-dir-nameto-file-name]'
else:
iflen(sys.argv)!=3:
interactive=1
fromdir=raw_input('Directorycontainingpartfiles?')
tofile=raw_input('Nameoffiletoberecreated?')
else:
interactive=0
fromdir,tofile=sys.argv[1:]
absfrom,absto=map(os.path.abspath,[fromdir,tofile])
print'Joining',absfrom,'tomake',absto
try:
join(fromdir,tofile)
except:
print'Errorjoiningfiles:'
printsys.exc_info()[0],sys.exc_info()[1]
else:
print'Joincomplete:see',absto
ifinteractive:raw_input('PressEnterkey')#pauseifclicked
希望本文所述对大家的Python程序设计有所帮助。