0

I'm writing a script to parse an email, but there is some SyntaxError on the for loop in the following part:

def main():
     writer = csv.DictWriter(open('features.csv', 'w'), list(EXTRACTS.keys()))
     for mail in os.listdir(MAILDIR):
         writer.writerow({
                key: value(email.message_from_file(open(os.path.join(MAILDIR, mail), 'r')))
            for key, value in EXTRACTS.items()
             })

Please help me out of this!

EDIT:

File "/IS/extraction.py", line 52

for key, value in EXTRACTS.items()
  ^ SyntaxError: invalid syntax
4
  • value(email.message_from_file(open(os.path.join(MAILDIR, mail), 'r'))) doesnt look right. what are you trying to do? Commented Oct 18, 2013 at 19:05
  • @karthikr: It's fine if the values in the EXTRACTS dictionary are callable. Commented Oct 18, 2013 at 19:06
  • For future reference, please do include the full traceback of your exception, to make it easier for us to diagnose your problem. Commented Oct 18, 2013 at 19:07
  • In that line the script should read all the mails (found in the MAILDIR) and get the values we have to inspect (for example sender, IP, subject,...) Commented Oct 18, 2013 at 19:07

1 Answer 1

2

You are running this on an older Python version that doesn't yet support dict comprehensions. The {key: value for ... in ...} syntax is only available in Python 2.7 and newer:

Python 2.6.8 (unknown, May 22 2013, 11:58:55) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def main():
...      writer = csv.DictWriter(open('features.csv', 'w'), list(EXTRACTS.keys()))
...      for mail in os.listdir(MAILDIR):
...          writer.writerow({
...                 key: value(email.message_from_file(open(os.path.join(MAILDIR, mail), 'r')))
...             for key, value in EXTRACTS.items()
  File "<stdin>", line 6
    for key, value in EXTRACTS.items()
      ^
SyntaxError: invalid syntax

Replace the line with a dictionary constructor and a generator expression:

writer.writerow(dict(
    (key, value(email.message_from_file(open(os.path.join(MAILDIR, mail), 'r'))))
    for key, value in EXTRACTS.items()
))

You do want to avoid reading the email message for every key-item pair in EXTRACTS though; read it once per outer loop:

def main():
    writer = csv.DictWriter(open('features.csv', 'w'), list(EXTRACTS.keys()))
    for mail in os.listdir(MAILDIR):
        mail = email.message_from_file(open(os.path.join(MAILDIR, mail), 'r'))
        writer.writerow(dict((key, value(mail)) for key, value in EXTRACTS.items()))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.