Why does my code only write the last line?
Question: I'm writing a list to file but it only writes the last line.

Here is my code. I'm on Python 2.7.

    
    
    server=os.listdir('.') #contents of the current directory
    for files in server:
        public_html = []
        if os.path.isfile(files) == True :
            pass
        elif os.path.isdir(files) == True :
            public_html.insert(0, files)
            print public_html
            f = open("index.html","w")
            f.write("<html>\n<head>\n<meta charset='utf-8'>\n<title></title>\n<link rel='stylesheet' href='css/normalize.css'>\n<script src=''></script></head>\n<body>")
            for folder in public_html:
                print folder
                f.write("<a>" + folder + "<a/>" + "\n")
                f.close()
    


Answer: Whenever you do `open('path/to/file',"w")` it blanks the file before writing
to it. This is called "write mode" and more info can be found [in the
docs](http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-
files). Instead, open the file in "append mode" (`'a'`), like this:

    
    
    ...
    elif os.path.isdir(files): # == True is redundant here
        public_html.insert(0,files)
        print public_html
        f = open('index.html','a')
        ...
    

In addition, you're trying to close your file object in every iteration
through your `public_html` list! This won't work, and will probably throw
exceptions when you try to call `write` on a closed object. Dedent that once
so it's after your loop

    
    
    for folder in public_html:
        print folder
        f.write("<a>" + folder + "<a/>" + "\n")
    f.close()
    

THAT BEING SAID, I think you're mostly going about this the wrong way...

    
    
    from bs4 import BeautifulSoup # http://www.crummy.com/software/BeautifulSoup/
    
    directories = [dir_ for dir_ in os.listdir('.') if os.path.isdir(dir_)]
    soup = BeautifulSoup("<html>\n<head>\n<meta charset='utf-8'>\n<title></title>\n<link rel='stylesheet' href='css/normalize.css'>\n<script src=''></script></head>\n<body>")
    
    for directory in directories:
        tag = soup.new_tag('a') # can do ('a', href='link/path')
        tag.string = directory
        soup.body.append(tag)
    with open('index.html','w') as index:
        index.write(soup.prettify())
    

This is more useful because you can more-easily control the contents of the
HTML, including throwing `href` on those `<a>`s!

