How to get key values when iterating a mailbox?

T

tinnews

I'm trying to delete some messages from a mailbox when they are older
than a certain number of days.

If I iterate through the mailbox and find a message that needs
deleting how do I get its key so I can do "remove(key)"?

The trouble is that, as the documentation says: "The default Mailbox
iterator iterates over message representations, not keys as the
default dictionary iterator does." So if you try something like:-

for f in os.listdir(junkdir):
mbxPath = os.path.join(junkdir, f)
mbx = mailbox.mbox(mbxPath, factory=None)
mbx.lock()
for k, msg in mbx:
if <something is true>
msg.remove(k)
mbx.flush()
mbx.unlock()

Then you get an exception on "for k, msg in mbx" which is an attribute
error, presumably because a mailbox isn't a 'real' iterator. So how,
do I get that key value?
 
C

Chris Rebert

I'm trying to delete some messages from a mailbox when they are older
than a certain number of days.

If I iterate through the mailbox and find a message that needs
deleting how do I get its key so I can do "remove(key)"?

The trouble is that, as the documentation says: "The default Mailbox
iterator iterates over message representations, not keys as the
default dictionary iterator does." So if you try something like:-

   for f in os.listdir(junkdir):
       mbxPath = os.path.join(junkdir, f)
       mbx = mailbox.mbox(mbxPath, factory=None)
       mbx.lock()
       for k, msg in mbx:
           if <something is true>
               msg.remove(k)
       mbx.flush()
       mbx.unlock()

Then you get an exception on "for k, msg in mbx" which is an attribute
error, presumably because a mailbox isn't a 'real' iterator.

No, it's probably because iterating over a Mailbox yields Message-s
rather than (key, Message) pairs; Python thus tries to unpack each
Message into a (k, msg) pair (since that's how you wrote your
for-loop), but this fails since (I would assume) Messages aren't
iterable.
So how,
do I get that key value?

If you want to iterate over key-value pairs (aka "items"), then ask
Mailbox for items in the first place:

for k, msg in mbx.iteritems():
# rest of code

Cheers,
Chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,981
Messages
2,570,188
Members
46,731
Latest member
MarcyGipso

Latest Threads

Top