11 from optparse
import OptionParser
19 def writefile(ipath, opath, startpos, endpos) :
23 fin = open(ipath,
"r") 25 print(
'Error: could not open "%s".' % ipath)
29 fout = open(opath,
"w")
31 print(
'Error: could not open "%s".' % opath)
35 remain = endpos - startpos
40 buf = fin.read(bufsize)
56 def getcuttingpoint(ipath, sep, startpos, partsize) :
59 filesize = os.path.getsize(ipath)
60 if startpos + partsize > filesize :
64 endpos = startpos + partsize
65 if endpos + bufsize > filesize :
66 bufsize = filesize - endpos
70 print(
'Error: could not open "%s".' % ipath)
80 print(
"Separator not found in proper position.\n")
93 def splitfile(nums, sep, odir, opref, infile) :
95 filesize = os.path.getsize(infile)
96 partsize = filesize // nums
98 print(
"Splitting file: ")
99 for i
in range(nums-1) :
100 endpos = getcuttingpoint(infile, sep, startpos, partsize)
105 opath = os.path.join(odir, (opref + suffix))
107 writefile(infile, opath, startpos, endpos)
109 sys.stdout.write(
'.')
113 suffix =
"%06d" % (nums-1)
114 opath = os.path.join(odir, (opref + suffix))
115 writefile(infile, opath, startpos, filesize)
121 if __name__ ==
"__main__":
123 usage =
"usage: %prog [options] inputfile" 124 parser = OptionParser(usage)
126 parser.add_option(
"-n",
130 help=
"number of file separation",
134 parser.add_option(
"-s",
138 help=
"separator string",
142 parser.add_option(
"-d",
143 "--output-directory",
146 help=
"output directory",
150 parser.add_option(
"-p",
151 "--output-file-prefix",
154 help=
"output filename prefix",
158 parser.add_option(
"-f",
165 (options, args) = parser.parse_args()
169 parser.error(
"missing parameter")
174 if not os.path.exists(inputfile) :
175 print(
'Error: inputfile %s is not exist.' % inputfile)
178 if os.path.exists(options.odir) :
179 if not os.path.isdir(options.odir) :
180 print(
'Error: "%s" is not directory.' % options.odir)
185 os.mkdir(options.odir)
187 print(
'Error: could not create "%s".' % options.odir)
190 print(
'Error: directory "%s" is not exist. create it or use -f option.' % options.odir)
193 splitfile(options.nums, options.sep, options.odir, options.opref, inputfile)