from os import mkdir,getcwd
from os.path import join,dirname,isdir
from sys import argv
from math import log10,pow
# Check for the correct number of agruments
# Print a help message if they are incorrect
if len(argv) != 3:
print 'syntax: python aiebr2.py <maximum characters> <file to split>'
print 'NOTE: The maximum characters does not account for post links, or'
print 'part numbering, please account for this when choosing a length'
else:
# Interpret the user input
max_chars = int(argv[1])
file_to_split = argv[2]
# Read the story as a collection of lines
story = []
story_length = 0;
with open(file_to_split, 'r') as story_file:
while True:
line = story_file.readline()
if line != "":
story.append(line)
story_length += len(line)
else:
break
# Build a set of parts by adding each line to a part, creating a
# new part if adding that line would go over the maximum character
# limit
parts = []
current_length = 0
current_part = ""
for line in story:
if current_length+len(line) > max_chars:
parts.append(current_part)
current_part = line
current_length = len(line)
else:
current_part += line
current_length += len(line)
if current_part != "":
parts.append(current_part)
# Create a directory for the parts
total_parts = len(parts)
story_dir = dirname(file_to_split);
if story_dir == "":
story_dir = os.getcwd()
parts_dir = join(story_dir,file_to_split+'_parts')
if not isdir(parts_dir):
mkdir(parts_dir)
# For each part, make a file in that directory with the contents
# as well as a x/y numbering at the bottom
for i in range(0,len(parts)):
part = parts[i]
part_path = join(parts_dir, str(i+1)+'.txt')
with open(part_path,'w') as part_file:
numbering = '\n'+str(i+1)+'/'+str(total_parts)
to_write = part+numbering
chars_written = len(to_write)
part_file.write(to_write)
print 'part '+str(i+1)+ ' is '+str(chars_written)+ ' characters long'
print 'done'