-
Notifications
You must be signed in to change notification settings - Fork 0
/
extractor.py
executable file
·40 lines (32 loc) · 1.46 KB
/
extractor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/env python
import argparse
import contextlib
import csv
import os
import sqlite3
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='''A script that extracts contents from a csv file
into an sqlite database''')
parser.add_argument('csv_file',
type=argparse.FileType('r'),
help='Csv file to be imported')
args = parser.parse_args()
db_name = '{}.db'.format(os.path.basename(args.csv_file.name))
# When used as a context manager, a sqlite connection already commits
# the transaction, yet it does not close it. That's why it is used
# combined with contextlib.closing
with args.csv_file as csv_file,\
contextlib.closing(sqlite3.connect(db_name)) as conn,\
conn as connection:
rows = csv.reader(csv_file, skipinitialspace=True)
cursor = connection.cursor()
cursor.execute(""" CREATE TABLE IF NOT EXISTS person (
time timestamp PRIMARY KEY,
name varchar NOT NULL,
age integer
); """)
cursor.executemany('insert or ignore into person values (?,?,?)', rows)
print('{} values inserted'.format(cursor.rowcount))
entries = cursor.execute("select count(*) from person").fetchone()[0]
print('Total of {} entries'.format(entries))