用于项目列表的 Python,到单个字符串?

标签 python list glob

只是想知道是否有人可以告诉我我做错了什么。 在我的 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

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

谢谢

最佳答案

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

关于用于项目列表的 Python,到单个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17245547/

相关文章:

c# - 使用 Linq 比较 2 列表中的字符串

php - 使用 CodeIgniter 的多级列表

Perl glob、qq() 和方括号 []

regex - 从字符串中切出一段并返回相反的部分

python - k-means 聚类中 holdout 集的目的是什么?

python - 在 Python 中确定文件系统的簇大小

python - 如何通过对嵌套列表中的单词进行词干处理来获取嵌套列表?

typescript - 指定的 glob 模式与任何文件都不匹配,或者默认测试目录为空。 - 测试咖啡馆

python - 如何在 celery 中禁止泡菜序列化

python - 如何通过Python执行任意shell脚本并传递多个变量?