我正在向文件写入一个列表,但它只写入最后一行。
这是我的代码。我使用的是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()
这是解决该问题的更简洁的方法:
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>
"""
def main():
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)
with open("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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)