9 from optparse
import OptionParser
17 def writefile(ipath, opath, startpos, endpos) :
21 fin = open(ipath,
"r") 23 print 'Error: could not open "%s".' % ipath
27 fout = open(opath,
"w")
29 print 'Error: could not open "%s".' % opath
33 remain = endpos - startpos
38 buf = fin.read(bufsize)
54 def getcuttingpoint(ipath, sep, startpos, partsize) :
57 filesize = os.path.getsize(ipath)
58 if startpos + partsize > filesize :
62 endpos = startpos + partsize
63 if endpos + bufsize > filesize :
64 bufsize = filesize - endpos
68 print 'Error: could not open "%s".' % ipath
78 print "Separator not found in proper position.\n" 91 def splitfile(nums, sep, odir, opref, infile) :
93 filesize = os.path.getsize(infile)
94 partsize = filesize / nums
96 print "Splitting file: ",
97 for i
in range(nums-1) :
98 endpos = getcuttingpoint(infile, sep, startpos, partsize)
103 opath = os.path.join(odir, (opref + suffix))
105 writefile(infile, opath, startpos, endpos)
107 sys.stdout.write(
'.')
111 suffix =
"%06d" % (nums-1)
112 opath = os.path.join(odir, (opref + suffix))
113 writefile(infile, opath, startpos, filesize)
119 if __name__ ==
"__main__":
121 usage =
"usage: %prog [options] inputfile" 122 parser = OptionParser(usage)
124 parser.add_option(
"-n",
128 help=
"number of file separation",
132 parser.add_option(
"-s",
136 help=
"separator string",
140 parser.add_option(
"-d",
141 "--output-directory",
144 help=
"output directory",
148 parser.add_option(
"-p",
149 "--output-file-prefix",
152 help=
"output filename prefix",
156 parser.add_option(
"-f",
163 (options, args) = parser.parse_args()
167 parser.error(
"missing parameter")
172 if not os.path.exists(inputfile) :
173 print 'Error: inputfile %s is not exist.' % inputfile
176 if os.path.exists(options.odir) :
177 if not os.path.isdir(options.odir) :
178 print 'Error: "%s" is not directory.' % options.odir
183 os.mkdir(options.odir)
185 print 'Error: could not create "%s".' % options.odir
188 print 'Error: directory "%s" is not exist. create it or use -f option.' % options.odir
191 splitfile(options.nums, options.sep, options.odir, options.opref, inputfile)