Skip to content

Instantly share code, notes, and snippets.

@RMuskovets
Created November 6, 2017 18:43
Show Gist options
  • Save RMuskovets/92e73c367fd3c256a232d942097ee91d to your computer and use it in GitHub Desktop.
Save RMuskovets/92e73c367fd3c256a232d942097ee91d to your computer and use it in GitHub Desktop.
A Python 3.6 program that splits one file to some .txt documents with specified length in lines
#!/usr/bin/env python3
from urllib.request import urlopen
def slicefile(data, start, end):
import itertools
lines = data.splitlines()
return itertools.islice(lines, start, end)
def pages(data, lines):
count = 0
start, end = 0, lines
while end <= len(data.splitlines()):
aline = list(slicefile(data, start, end))
with open('page-{}.txt'.format(count), 'w') as x:
for line in aline:
x.write(line + '\n')
x.close()
start, end = end, end+lines
count += 1
def in_web(filename, lines):
response = urlopen(filename)
content = response.read()
pages(content, lines)
def in_disk(filename, lines):
pages(open(filename).read(), lines)
from argparse import *
parser = ArgumentParser(description='Convert file to pages.')
parser.add_argument('-w', '--web', help='Find file in the web.', action='store_true')
parser.add_argument('file', help='File name or URL')
parser.add_argument('lines', help='Number of lines in one page', type=int)
args = parser.parse_args()
if args.web:
in_web(args.file, args.lines)
else:
in_disk(args.file, args.lines)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment