Fractionfiles.py
Join the DZone community and get the full member experience.
Join For Free// Splits a file into smaller ones, and joins them together.
#!/usr/bin/env python
"""Splits and joins files. Helpful when media can't fit a file.
Be prepared for a lot of output files!"""
__author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
__date__="6 Jan 3006 - 12 Feb 2006"
__copyright__="Copyright 2006 Andrew Pennebaker"
__version__="0.3"
__URL__="http://snippets.dzone.com/posts/show/3541"
import sys, os
from getopt import getopt
SPLIT_MODE="SPLIT"
JOIN_MODE="JOIN"
def splitFile(name, length, number):
if length==None:
infile=open(name, "rb")
size=0
while infile.read(1)!="":
size+=1
infile.close()
maxlength=size/number
if number*maxlength"
print "--join "
print "--maxlength "
print "--maxfiles "
print "--help (usage)"
sys.exit()
def main():
global SPLIT_MODE
global JOIN_MODE
mode=SPLIT_MODE
filenames=[]
maxlength=1024
maxfiles=None
systemArgs=sys.argv[1:] # ignore program name
optlist=[]
args=[]
try:
optlist, args=getopt(systemArgs, None, ["split", "join", "maxlength=", "maxfiles=", "help"])
except Exception, e:
usage()
if len(optlist)<1 or len(args)<1:
usage()
for option, value in optlist:
if option=="--help":
usage()
elif option=="--split":
mode=SPLIT_MODE
elif option=="--join":
mode=JOIN_MODE
elif option=="--maxlength":
try:
maxlength=int(value)
if maxlength<1:
raise Exception
maxfiles=None
except Exception, e:
raise "Length must be at least one"
elif option=="--maxfiles":
try:
maxfiles=int(value)
if maxfiles<1:
raise Exception
maxlength=None
except Exception, e:
raise "Number must be at least one"
filenames=args
if mode==SPLIT_MODE:
for filename in filenames:
try:
splitFile(filename, maxlength, maxfiles)
except Exception, e:
raise e
elif mode==JOIN_MODE:
for directory in filenames:
files=["%s%s%s" % (directory, os.sep, file) for file in os.listdir(directory)]
try:
joinFiles(files)
except Exception, e:
raise e
if __name__=="__main__":
main()
Opinions expressed by DZone contributors are their own.
Comments