Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting text file to html file with python

Tags:

python

html

text

I have a text file that contains :

JavaScript              0
/AA                     0
OpenAction              1
AcroForm                0
JBIG2Decode             0
RichMedia               0
Launch                  0
Colors>2^24             0
uri                     0

I wrote this code to convert the text file to html :

contents = open("C:\\Users\\Suleiman JK\\Desktop\\Static_hash\\test","r")
    with open("suleiman.html", "w") as e:
        for lines in contents.readlines():
            e.write(lines + "<br>\n")

but the problem that I had in html file that in each line there is no space between the two columns:

JavaScript 0
/AA 0
OpenAction 1
AcroForm 0
JBIG2Decode 0
RichMedia 0
Launch 0
Colors>2^24 0
uri 0 

what should I do to have the same content and the two columns like in text file

like image 734
user3832061 Avatar asked Jul 12 '14 16:07

user3832061


People also ask

Can Python output to HTML?

Python language has great uses today in almost every field, it can be used along with other technologies to make our lives easier. One such use of python is getting the data output in an HTML file. We can save any amount of our input data into an HTML file in python using the following examples in two ways.


2 Answers

Just change your code to include <pre> and </pre> tags to ensure that your text stays formatted the way you have formatted it in your original text file.

contents = open"C:\\Users\\Suleiman JK\\Desktop\\Static_hash\\test","r")
with open("suleiman.html", "w") as e:
    for lines in contents.readlines():
        e.write("<pre>" + lines + "</pre> <br>\n")
like image 189
雨が好きな人 Avatar answered Oct 18 '22 03:10

雨が好きな人


This is HTML -- use BeautifulSoup

from bs4 import BeautifulSoup

soup = BeautifulSoup()
body = soup.new_tag('body')
soup.insert(0, body)
table = soup.new_tag('table')
body.insert(0, table)

with open('path/to/input/file.txt') as infile:
    for line in infile:
        row = soup.new_tag('tr')
        col1, col2 = line.split()
        for coltext in (col2, col1): # important that you reverse order
            col = soup.new_tag('td')
            col.string = coltext
            row.insert(0, col)
        table.insert(len(table.contents), row)

with open('path/to/output/file.html', 'w') as outfile:
    outfile.write(soup.prettify())
like image 42
Adam Smith Avatar answered Oct 18 '22 01:10

Adam Smith