gpt4 book ai didi

Python 属性错误 : 'str' object has no attribute 'namelist'

转载 作者:太空宇宙 更新时间:2023-11-04 01:30:22 25 4
gpt4 key购买 nike

我正在尝试在 python 中创建一个非常简单的日志解析器脚本。一切都按计划进行,除了目标机器上的脚本返回此错误(该脚本在 unix 机器上工作,但非常好):

for name in root.namelist():
Attribute Error: 'str' object has no attribute 'namelist'

Python 版本似乎相同(两台机器上都是 2.7.3)。有什么想法吗?

脚本本身:

import zipfile
import os
import re

string1 = "searchstring" # raw_input("usrinput: ")

try:
root = zipfile.ZipFile("/home/testuser/docs/testzip.zip", "r")
except:
root = "testfolder/"
for name in root.namelist():
if name.find(".") > 0:
f = root.open(name)
searchlines = f.readlines()
for i, line in enumerate(searchlines):
regex1 = "(.*)" + re.escape(string1) + "(.*)"
if re.match (regex1, line):
for l in searchlines[i-4:i+4]: print l,
print

最佳答案

这是因为 root = "testfolder/" 它没有任何名称列表作为它的属性。

根的类型是字符串

反过来看你的代码意味着,root = zipfile.ZipFile("/home/testuser/docs/testzip.zip", "r") 产生了一个异常

在异常 block 中尝试使用 except Exception, ex: 然后打印 ex.message 以了解生成的异常类型

关于Python 属性错误 : 'str' object has no attribute 'namelist' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14253412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com