I am wondering how to write a list to an html file from scratch. I am currently writing it to a file using:

def wpubooks(self):
        for i in booklist:
	    f=open('/booklist', 'a')
	    f.write(i + '\n')

Is there a way I can change that code so that it writes to an html file instead?

first, you need to open the file as a html file like this:

file = open('mfile.htm', 'a')

im not sure how you would use a form but its a start

Hi, thanks for that.

I now have:

fin = open("booklist.txt")
fout = open('/booklist.htm', 'w')


fout.write("<h1>Here is a list of books in the library</h1>")


for line in fin:
    fout.write("\t<li>%s</li>\n" % line)




My list of books is in booklist.txt. The code I use to write to booklist.txt is

def wpubooks(self):
        for i in booklist:
	    f=open('/booklist.txt', 'a')
	    f.write(i + '\n')

Each time I run that bit it adds all the books in the book list to booklist.txt. How can I make it only add books which aren't already in booklist.txt? For example the booklist.txt contains:
and the list of books I have to add is book1 book3 book4, I only want it to add book4 as book1 and book3 already exist in booklist.txt.

A good rule of thumb: Get your data (whether it be from a file, user input, etc...) and THEN do stuff to it. It looks like you're trying to open your input file and also write to your output at the same time.

So, if booklist.txt looks like this:


Get a "booklist" like this:

book_file = open('booklist.txt','r')
#reads the file and splits it by line
booklist = book_file.read().split('\n')

Now that you've got your booklist, you can add to it, subtract from it, and do all sorts of fun stuff to it. So, if the books I had to add were in a list called addlist:

>>> addlist = ['book1','book5','book4'] #note that book 1 is already in the file
>>> #also, note that this is the list we got from the file:
>>> booklist = ['book1','book2','book3']
>>> mydict = {}
>>> for book in booklist:
	mydict[book] = 1 #put all your books in a dict to remove duplicates

>>> for book in addlist:
	mydict[book] = 1

>>> print mydict.keys()
['book1', 'book2', 'book3', 'book4', 'book5']
>>> #yay! notice that book1 is only listed once

Then, write mydict.keys() to your html file, or back into your text file, or whatever you're doing with it. Note that [inline]book_file = open('booklist.txt','w')[/inline] will overwrite whatever was there previously.

In short, keep your input, your functionality, and your output separate, and things will generally be easier.