All pastes #1626690 Raw Edit

Unwrap Text

public python v1 · immutable
#1626690 ·published 2009-10-18 06:44 UTC
rendered paste body
import sysfrom optparse import OptionParserdef unwrap(column, infile, outfile):    lines = infile.readlines()    if lines[0].startswith('\xef\xbb\xbf'): # UTF-8 BOM        lines[0] = lines[0][3:]    for counter in range(len(lines)):        line = lines[counter]        if counter < len(lines) - 1: nextline = lines[counter+1]        else: nextline = ''        if line.strip() == '' or nextline.strip() == '':            outfile.write(line) # Don't unwrap if there's a blank line        elif len(line) >= column: # Use >= instead of > since there's also a newline character            outfile.write(line.rstrip() + ' ')        else:            outfile.write(line + '\n') # Add blank linedef main(argv):    """%prog [options] input.txt [output.txt]"""    parser = OptionParser(usage=main.__doc__)    parser.add_option('-c', '--column', type='int', default=72,                      help='Lines exceeding this width will be unwrapped with next [default %default]')    (options, parms) = parser.parse_args(argv[1:])    if len(parms) == 1:        return unwrap(options.column, open(parms[0], 'r'), sys.stdout)    elif len(parms) == 2:        return unwrap(options.column, open(parms[0], 'r'), open(parms[1], 'w'))    else:        print >> sys.stderr, "Syntax: %s" % main.__doc__.replace('%prog', argv[0])        return 1if __name__=='__main__':    sys.exit(main(sys.argv))