Why Does My Code Only Write The Last Line?
Solution 1:
Here is a tidier way of approaching the problem:
import os
LINK = ' <a href="{href}">{txt}</a>'
TEMPLATE = """<html>
<head>
<meta charset="utf-8">
<title>{title}</title>
<link rel="stylesheet" href="{stylesheet}"/>
</head>
<body>
{content}
</body>
</html>
"""defmain():
dirs = [fname for fname in os.listdir(".") if os.path.isdir(fname)]
dirs.sort() # in alphabetical order
content = "\n".join(LINK.format(href=os.path.abspath(dirname), txt=dirname) for dirname in dirs)
withopen("index.html", "w") as outf:
fields = {
"title": "My Directory List",
"stylesheet": "css/normalize.css",
"content": content
}
outf.write(TEMPLATE.format(**fields))
if __name__=="__main__":
main()
Solution 2:
Your call to f.close()
is inside the for
. Should be outside
Solution 3:
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. 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!
Solution 4:
this his the code i end up doing from the answers posted above also this version his ported to python 3.4 might be usefull to someone.
LINK = '<liclass="{webapp_name}"><h2>{webapp_name}</h2><ahref="{href}{webapp_name}/"><imgsrc="./assets/images/text-html.png"></img></a></li>'
TEMPLATE = """{document}
<html><head><metacharset="utf-8"><width></width><height></height><title>My Web Apps</title><linkrel="stylesheet"href="{stylesheet}"/></head><body><ulclass="websites">
{content}
</ul></body></html>
"""
def create_html():
wrkDir = os.getenv('HOME') + ("/Documents/Workspace")
directory = [folder for folder in os.listdir(wrkDir) if os.path.isdir(wrkDir)]
directory.sort() # in alphabetical order
server_links = "\n".join(LINK.format(href='http://localhost/', webapp_name=directory_name)
for directory_name in directory)
with open("index.html", "w") as index:
fields = {
"document": "<!DOCTYPE html>",
"stylesheet": "assets/style.css",
"content": server_links
}
soup = BeautifulSoup(TEMPLATE.format(**fields))
index.write(soup.prettify())
if __name__=="__main__":
create_html()
Post a Comment for "Why Does My Code Only Write The Last Line?"