DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Tvrtko has posted 6 posts at DZone. View Full User Profile

Code 2 HTML

04.07.2008
| 5031 views |
  • submit to reddit
        This is a simple python program that reads a file (code), and replaces line breaks and spaces with appropriate tag and entity.

import sys

line_break='<br>'
nb_space=' '

def toHtml(f,out):
    try:
        fo=open(out,'w')
    except IOError:
        print 'output file error!'
    else:
        for line in f:
            line=line.replace('\t',nb_space*8)
            line=line.replace(' ',nb_space)
            line=line.replace('\n',line_break)
            fo.write(line)
        fo.close()
        

if len(sys.argv) == 1:
    print("at least one argument / input filename / required")
    sys.exit()
if len(sys.argv) > 3:
    print"too many arguments"
    sys.exit()       
try:
    f=open(sys.argv[1],'r')
except IOError:
    print 'cannot open file ', sys.argv[1]
else:
    if len(sys.argv) == 2:
        out=f.name + '.html'
    else:
        out=sys.argv[2]
    toHtml(f, out)
    f.close()