【问题标题】:Python for items list, to indivdual string?用于项目列表的 Python 到单个字符串?
【发布时间】:2013-06-21 23:06:31
【问题描述】:

只是想知道是否有人可以告诉我我做错了什么。 处理一些代码,与我的cherrypy项目一起使用

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

我认为是因为我传递的文件名在字符串的列表中包含 [' 和 '], 我可以编写一个函数来修剪这些部分,但这是唯一的选择,或者我在做一些愚蠢的事情。

谢谢

【问题讨论】:

    标签: python list glob


    【解决方案1】:
    myArticles = [glob.glob(article_path)]
    

    应该是:

    myArticles = glob.glob(article_path)
    

    glob.glob 返回一个列表,通过在其周围添加[] 可以使其成为列表列表。

    所以,在这个循环中:

    for items in myArticles:
        get_html(items)
    

    您实际上将整个列表传递给 get_html 并且 open 引发了该错误。

    演示:

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

    【讨论】:

    • 啊,明白了,谢谢你:)
    猜你喜欢
    • 2021-04-12
    • 1970-01-01
    • 2016-03-29
    • 2018-10-15
    • 2011-01-08
    • 2023-03-23
    • 2015-09-21
    • 1970-01-01
    相关资源
    最近更新 更多