More examples of comma separated value (CSV) data
A comma separated values (CSV) file is a plain text file, that normally uses a comma to separate each specific data value, for example:colA,colB,colC row1dataA,row1dataB,row1dataC row2dataA,row2dataB,row2dataC
The (CSV) file we are using in the following example (when opened on disk) looks like this:
Game,Released Skyrim,11-Nov-11 Minecraft,17-May-09 Fortnite,25-Jul-17
CSV.py
import requests import csv #1. get a csv file: url = "http://www.digisoln.com/games.csv" download = requests.get(url) #2. write csv data to a file, and save file to disk: with open('games.csv', 'w', newline='') as file: writer = csv.writer(file) reader = csv.reader(download.text.splitlines()) for row in reader: writer.writerow(row) #3. map a csv file from disk to a dictionary: with open('games.csv') as csvfile: anotherReader = csv.DictReader(csvfile) for eachRow in anotherReader: print(eachRow['Game'], eachRow['Released'])
The second example below uses the driverdemographics.csv available here: https://data.qld.gov.au/dataset/crash-data-from-queensland-roads:
CSV.py
import csv import sqlite3 #download driverdemographics.csv from: #https://data.qld.gov.au/dataset/crash-data-from-queensland-roads createSQLqueryString = ''' CREATE TABLE IF NOT EXISTS crashData( id INTEGER NOT NULL PRIMARY KEY, Crash_Year INTEGER, Crash_Police_Region TEXT, Crash_Severity TEXT, Count_Casualty_All INT); ''' insertSQLqueryString = ''' INSERT INTO crashData( Crash_Year, Crash_Police_Region, Crash_Severity, Count_Casualty_All ) values (?, ?, ?, ?); ''' try: db = sqlite3.connect('roadcrashes.db') cursor = db.cursor() cursor.execute(createSQLqueryString) cursor.execute("SELECT * FROM crashData") result = cursor.fetchall() if not(len(result) > 0): #empty: with open('driverdemographics.csv') as csvfile: reader = csv.DictReader(csvfile) for each in reader: cursor.execute(insertSQLqueryString, (each['Crash_Year'], each['Crash_Police_Region'], each['Crash_Severity'], each['Count_Casualty_All'])) db.commit() print("Database was created, and records were inserted.") except Exception as error: db.rollback() print("Something went wrong: " + str(error)) finally: db.close()