2014-02-23 51 views
-2

我在寫文件列表,但只寫最後一行。爲什麼我的代碼只寫最後一行?

這是我的代碼。我在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() 
+0

什麼是輸出? – slezica

回答

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

(至少在Windows中...)'os.listdir'無論如何返回一個排序列表。事實上,由於''Z「<」_「<」a「''''''dirs.sort'通常不會做你想做的事,所以你將擁有'['驚人的','名字','Of'斑馬「,」_動物學「,」_ argh「,」酒吧「,」foo「]'這絕對不會被分類! –

+0

即時在Linux上它不需要排序所有它取得文件夾列表製作一個鏈接並將其發送到webkit webview並創建一個窗口使用gtk它是一個簡單的Web開發機器的前端。 – codesardine

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時可能會引發異常。迪登一旦所以它是你的循環

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> s!

+1

我想給你另一個BeautifulSoup upvote,但我不能: -/ –

+1

即將與BeautifulSoup一起閱讀關於它,併爲這個場合思考他正是我所需要的。坦克大家的幫助。 – codesardine

1

您致電f.close()位於for之內。外應

+0

我通常這樣做他的我的1 python程序仍然在努力 – codesardine

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()   
相關問題