Skip to content

Instantly share code, notes, and snippets.

@ptbrowne
Created September 6, 2016 12:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ptbrowne/206e37bf765e0bc924fe4be4c210fe4f to your computer and use it in GitHub Desktop.
Save ptbrowne/206e37bf765e0bc924fe4be4c210fe4f to your computer and use it in GitHub Desktop.
Parse mailFilters.xml from Gmail to CSV, only supports to and forwardTo
from collections import defaultdict
from xml.etree import cElementTree as ET
def etree_to_dict(t):
# remove namespace
if hasattr(t.tag, 'find'):
i = t.tag.find('}')
if i >= 0:
t.tag = t.tag[i+1:]
d = {t.tag: {} if t.attrib else None}
children = list(t)
if children:
dd = defaultdict(list)
for dc in map(etree_to_dict, children):
for k, v in dc.items():
dd[k].append(v)
d = {t.tag: {k:v[0] if len(v) == 1 else v for k, v in dd.items()}}
if t.attrib:
d[t.tag].update(('@' + k, v) for k, v in t.attrib.items())
if t.text:
text = t.text.strip()
if children or t.attrib:
if text:
d[t.tag]['#text'] = text
else:
d[t.tag] = text
return d
e = ET.XML(open('mailFilters.xml').read())
d = etree_to_dict(e)
def get_entries():
yield 'to,forwardTo'
for entry in d['feed']['entry']:
properties = entry['property']
data = {}
for p in properties:
data[p['@name']] = p['@value']
if data.get('to') and data.get('forwardTo'):
yield '%s,%s' % (data['to'], data['forwardTo'])
yield ''
with open('result.csv', 'w+') as r:
r.write('\n'.join(list(get_entries())))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment