Created
May 23, 2021 08:58
-
-
Save kissgyorgy/9540539532836e9df8b3234cf7d316f5 to your computer and use it in GitHub Desktop.
Python: CSV challenge (https://gist.github.com/jorinvo/2e43ffa981a97bc17259)
This file contains hidden or 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
import requests | |
import datetime | |
URI = 'https://gist.githubusercontent.com/jorin-vogel/7f19ce95a9a842956358/raw/e319340c2f6691f9cc8d8cc57ed532b5093e3619/data.json' | |
filename = datetime.date.today().strftime('%Y%m%d.csv') | |
def imperative(): | |
with open(filename, 'w') as f: | |
f.write('Name,Credit Card\n') | |
for customer in requests.get(URI).json(): | |
if customer['creditcard']: | |
f.write('%(name)s,%(creditcard)s\n' % customer) | |
def functional(): | |
json_data = requests.get(URI).json() | |
affected_customers = (cust for cust in json_data if cust['creditcard']) | |
csv_lines = ('%(name)s,%(creditcard)s' % cust for cust in affected_customers) | |
with open(filename, 'w') as f: | |
f.write('Name,Credit Card\n') | |
f.write('\n'.join(csv_lines)) | |
def even_more_functional(): | |
json_data = requests.get(URI).json() | |
affected_customers = filter(lambda cust: cust['creditcard'], json_data) | |
csv_lines = ('%(name)s,%(creditcard)s' % cust for cust in affected_customers) | |
with open(filename, 'w') as f: | |
f.write('Name,Credit Card\n') | |
f.write('\n'.join(csv_lines)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment