python splitting text file by line reminders -
python splitting text file by line reminders -
i have created python programme count lines in text file split multi files depending on how much file numbers user asks have problem remainder of partition process when user asks split file 3 files script creates 4 files , write remaining lines in 4th file
my code :
num_lines = sum(1 line in open("perfix/{0}.txt".format(name))) size2 = num_lines / progs open('perfix/{0}.txt'.format(name)) f: i, g in enumerate(grouper(size2, f, fillvalue=''), 0): open('ip{0}_{1}'.format(name,(i+1)), 'w') fout: fout.writelines(g)
any way how can solve ?
thanks
if want lines written lastly file, size should different lastly one. 1 way can build array file sizes , if there remainder, append part size of lastly file. seems grouper custom function extending itertools. don't know does, here code out that. read many lines need initial file:
def filesplit(name,progs): num_lines = sum(1 line in open("{0}.txt".format(name))) extra=num_lines%progs #save remainder length sizes=[num_lines / progs ] * progs sizes[-1]=sizes[-1]+extra #add remainder lines length lastly file open('{0}.txt'.format(name)) f: i,g in enumerate(sizes): open('ip{0}_{1}'.format(name,(i+1)), 'w') fout: #read g lines f @ time , add together them new fout fout.writelines([next(f) x in xrange(g)])
python file text split
Comments
Post a Comment