"dictionary changed size during iteration" error in Python 3 but not in Python 2
Chris Green
cl at isbd.net
Sun Aug 23 05:00:50 EDT 2020
I have a (fairly) simple little program that removes old mail messages
from my junk folder. I have just tried to upgrade it from Python 2 to
Python 3 and now, when it finds any message[s] to delete it produces
the error:-
RuntimeError: dictionary changed size during iteration
I can sort of see why I'm getting the error but have two questions:
1 - Why doesn't it error in Python 2?
2 - How do I fix it?
Here is the program:-
#!/usr/bin/python3
#
#
# Remove old mail from mbox files
#
import email
import mailbox
import os
import sys
import time
#
#
# Constants/configuration
#
junkdir = "/home/chris/Mail/Ju" # directory to clear old mail from
days = 7 # remove mail older than this
#
#
#
#
for f in os.listdir(junkdir):
mbxPath = os.path.join(junkdir, f)
mbx = mailbox.mbox(mbxPath, factory=None)
try:
mbx.lock()
for k, msg in mbx.iteritems():
subject = msg['subject']
if msg['date'] is None:
continue
parsedDate = email.utils.parsedate(msg['date'])
if parsedDate is None:
print (subject + '\n - Bad date format:- "' + msg['date'] + '"')
continue
msgDate = time.mktime(parsedDate)
if (time.time() - msgDate) / (24 * 60 * 60) > days:
mbx.remove(k)
mbx.flush()
mbx.unlock()
except mailbox.ExternalClashError:
print ("Failed to lock: " + mbxPath)
--
Chris Green
ยท
More information about the Python-list
mailing list