Python循环以读取和解析目录中的所有内容

2024-04-27 03:19:20 发布

您现在位置:Python中文网/ 问答频道 /正文

class __init__:
    path = "articles/"
    files = os.listdir(path)
    files.reverse()

    def iterate(Files, Path):

        def handleXml(content):

            months = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

            parse = re.compile('<(.*?)>(.*?)<(.*?)>').findall(content)
            day = parse[1][1]
            month = months[int(parse[2][1])]
            dayN = parse[3][1]
            year = parse[4][1]
            hour = parse[5][1]
            min = parse[6][1]
            amPM = parse[7][1]
            title = parse[9][1]
            author = parse[10][1]
            article = parse[11][1]
            category = parse[12][1]

        if len(Files) > 5:
            del Files[5:]

        for file in Files:
            file = "%s%s" % (Path, file)
            f = open(file, 'r')
            handleXml(f.read())
            f.close()

    iterate(files, path)

它在start上运行,如果我检查files数组,它包含所有的文件名。 但当我循环使用它们时,它们就不起作用了,只显示第一个。 如果我返回file,我只得到前两个,如果我返回parse,即使在重复的文件上也不一样。 这些都没有任何意义。在

我试图用Python创建一个简单的blog,因为我的服务器有一个非常旧的Python版本,所以我不能使用像glob这样的模块,一切都需要尽可能基本。在

files数组包含目录中的所有文件,这对我来说已经足够好了。我不需要浏览文章目录中的其他目录。在

但是当我试图输出parse时,即使是在重复的文件上,我也会得到不同的结果。在

谢谢

  • 汤姆

Tags: 文件path目录parsedeffiles数组content
2条回答

可能是因为:

del Files[5:]

它也会从原始列表中删除最后5个条目。不使用del,您可以尝试:

^{pr2}$

如注释中所述,缺少实际递归。
即使它存在于代码的其他地方,递归调用也是出错的典型地方,因此我建议您仔细检查它。在

但是,为什么不使用os.walk?它遍历所有路径,而不需要重新创建(递归)轮子。不过,它已经在2.3中引入了,我不知道您的python有多老。在

相关问题 更多 >