import sys from optparse import OptionParser def 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 line def 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 1 if __name__=='__main__': sys.exit(main(sys.argv))