2013-06-21 19 views
3

只是想知道是否有人能夠友善地告訴我我做錯了什麼。 工作的一些代碼,在使用我的CherryPy項目Python的項目列表,以個人字符串?

import glob 
import os 

def get_html(apath): 
    print (apath) 
    fhtml = open(apath,'r') 
    data = fhtml.read() 

    return data 


article_path = os.getcwd() +'/articles/*.html' 
myArticles = [glob.glob(article_path)] 

print len(myArticles) 

for items in myArticles: 
    get_html(items) 

結果:

['/home/sd/Documents/projects/cherryweb/articles/Module 5-Exploitation Techniques And Exercise.pdf.html'] 
Traceback (most recent call last): 
    File "fntest.py", line 22, in <module> 
    get_html(items) 
    File "fntest.py", line 10, in get_html 
    fhtml = open(apath,'r') 
TypeError: coercing to Unicode: need string or buffer, list found 

我認爲它是因爲我傳遞的文件名有[「和」]從列表中在字符串上, 我可以編寫一個函數來修剪這些零件,但它是唯一的選擇,或者我是在做一些愚蠢的事情。

感謝

回答

3
myArticles = [glob.glob(article_path)] 

應該是:

myArticles = glob.glob(article_path) 

glob.glob返回一個列表,通過增加周圍[]你做它的目錄列表。

所以,在這個循環:

for items in myArticles: 
    get_html(items) 

你實際上傳遞的整個列表,以get_htmlopen引發的錯誤。

演示:

>>> open([]) 
Traceback (most recent call last): 
    File "<ipython-input-242-013dc85bc958>", line 1, in <module> 
    open([]) 
TypeError: coercing to Unicode: need string or buffer, list found 
+0

啊現貨上,感謝您的:) – whatsthatsay

相關問題