Repository navigation
Expand file tree
/
Copy pathexample.py
More file actions
69 lines (49 loc) · 1.5 KB
/
Copy pathexample.py
File metadata and controls
69 lines (49 loc) · 1.5 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# example.py
#
# Various samples of reading CSV files
import csv
# (a) Reading as tuples
print('Reading as tuples:')
with open('stocks.csv') as f:
f_csv = csv.reader(f)
headers = next(f_csv)
for row in f_csv:
# process row
print(' ', row)
# (b) Reading as namedtuples
print('Reading as namedtuples')
from collections import namedtuple
with open('stocks.csv') as f:
f_csv = csv.reader(f)
Row = namedtuple('Row', next(f_csv))
for r in f_csv:
row = Row(*r)
# Process row
print(' ', row)
# (c) Reading as dictionaries
print('Reading as dicts')
with open('stocks.csv') as f:
f_csv = csv.DictReader(f)
for row in f_csv:
# process row
print(' ', row)
# (d) Reading into tuples with type conversion
print('Reading into named tuples with type conversion')
col_types = [str, float, str, str, float, int]
with open('stocks.csv') as f:
f_csv = csv.reader(f)
headers = next(f_csv)
for row in f_csv:
# Apply conversions to the row items
row = tuple(convert(value) for convert, value in zip(col_types, row))
print(row)
# (e) Converting selected dict fields
print('Reading as dicts with type conversion')
field_types = [ ('Price', float),
('Change', float),
('Volume', int) ]
with open('stocks.csv') as f:
for row in csv.DictReader(f):
row.update((key, conversion(row[key]))
for key, conversion in field_types)
print(row)