Created
September 6, 2016 12:42
-
-
Save ptbrowne/206e37bf765e0bc924fe4be4c210fe4f to your computer and use it in GitHub Desktop.
Parse mailFilters.xml from Gmail to CSV, only supports to and forwardTo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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