2

I am trying to create a very simple log parser script in python. Everything is going as planned except the script on the target machine is returning this error (the script works on a unix machine though quite fine):

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

Python versions appear to be the same (2.7.3 on both machines). Any ideas?

Script itself:

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
3
  • It means the except block was executed and root is now a string "testfolder/". Jan 10, 2013 at 8:17
  • 1
    Pro tip: Don't use blanket except statements; you don't know what was wrong with your zipfile.ZipFile() call now.
    – Martijn Pieters
    Jan 10, 2013 at 8:17
  • hardcoding paths is never a good idea
    – asermax
    Jan 10, 2013 at 9:10

2 Answers 2

2

This is because root = "testfolder/" it doesn't have any namelist as its attribute.

Type of root is string

Which in turn looking at your code means, root = zipfile.ZipFile("/home/testuser/docs/testzip.zip", "r") generated an exception

in exception block try to use except Exception, ex: and then print ex.message to understand the type of exception being generated

1
  • Thanks everyone for the answers. I removed the whole Except, since I found out it is not necessary in this case. Real culprit was copying path to the zipfile from total commander on the windows machine. It somehow capitalized the folder name.
    – panta
    Jan 10, 2013 at 8:35
1

This is because, namelist() is only available for a zipfile, not for a string.

This happens when the zip file cannot be opened. Check the path where the zip file is located.

Try this and see the output:

try:
   root = zipfile.ZipFile("/home/testuser/docs/testzip.zip", "r")
except Exception, msg:
   print msg
   root = "testfolder/"

When I tried with a valid zip file, the program worked fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.