为什么我的代码只写最后一行?

时间:2014-02-23 17:43:02

标签: python

我正在写一个列表到文件,但它只写最后一行。

这是我的代码。我在使用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()

4 个答案:

答案 0 :(得分:2)

这是解决问题的更为简洁的方法:

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()

答案 1 :(得分:1)

每当你执行open('path/to/file',"w")时,它会在写入文件之前将文件空白。这称为“写入模式”,可以找到更多信息in the docs。而是以“追加模式”('a')打开文件,如下所示:

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

此外,您正试图通过public_html列表在每次迭代中关闭文件对象!这不起作用,当您尝试在已关闭的对象上调用write时,可能会抛出异常。 Dedent那曾经是你的循环之后

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

这就是说,我认为你主要以错误的方式解决这个问题......

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())

这更有用,因为您可以更轻松地控制HTML的内容,包括在href上投放<a>

答案 2 :(得分:1)

您对f.close()的来电位于for内。应该在外面

答案 3 :(得分:0)

这是我的代码,我最终在上面发布的答案中也做了这个版本,他移植到python 3.4可能对某人有用。

LINK = '<li class="{webapp_name}"><h2>{webapp_name}</h2><a href="{href}{webapp_name}/">       <img src="./assets/images/text-html.png"></img></a></li>'

TEMPLATE = """{document}
<html>
 <head>
   <meta charset="utf-8">
   <width></width><height></height>
   <title>My Web Apps</title>
   <link rel="stylesheet" href="{stylesheet}"/>
 </head>
   <body>
     <ul class="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()        
相关问题