Created
May 24, 2018 13:07
-
-
Save ntoll/fee452452dc3472486e804e52ac26cea to your computer and use it in GitHub Desktop.
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
CSV | |
==== | |
import csv | |
with open('swapi.csv') as f: | |
reader = csv.reader(f) | |
items = list(reader) | |
with open('swapi_new.csv', 'w') as f: | |
w = csv.writer(f) | |
for row in items: | |
w.writerow(row) | |
with open('swapi.csv') as f: | |
reader = csv.DictReader(f) | |
items = list(reader) | |
with open('swapi_new.csv') as f: | |
fieldnames = list[items[0].keys()] | |
w = csv.DictWriter(f, fieldnames=fieldnames) | |
w.writeheader() | |
for row in items: | |
w.writerow(row) | |
JSON | |
====== | |
import json | |
with open('swapi.json') as f: | |
items = json.load(f) | |
with open('new_swapi.json') as f: | |
json.dump(items, f) | |
XML | |
====== | |
DOM parsing: | |
from xml.etree import cElementTree as ET | |
xml = ET.parse('swapi.xml') | |
root = xml.getroot() | |
for child in root: | |
homeworld = child.find('homeworld').text | |
name = child.find('name').text | |
print(f"{name} is from {homeworld}") | |
Stream Parsing: | |
from xml.etree import cElementTree as ET | |
# Events defaults to "end" | |
xml_stream = ET.iterparse(open('swapi.xml'), events=("start", "end")) | |
for event, element in xml_stream: | |
if event == 'start': | |
# Element started... change state. | |
pass | |
else: | |
# Element ended (completed)... process and change state. | |
print(element.tag, element.text) | |
Plain text parsing: | |
======================= | |
with open('ueh_exception.log') as f: | |
lines = f.readlines() | |
len(lines) | |
lines[0] | |
l = lines[0] | |
elements = [e.strip() for e in l.strip(';')] | |
id, date, time, _ = elements[0].split(' ', 3) | |
id = id[:-1] | |
date = date[1:] | |
time = time[:-1] | |
dt = date + ' ' + time | |
import datetime | |
dt_obj = datetime.datetime.strptime(dt, "%Y-%m-%d %H:%M:%S.%f") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment