-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathreadcsv.py
65 lines (54 loc) · 1.65 KB
/
readcsv.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
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
# -*- coding: utf-8 -*-
import io
def readcsv(file, delimiter=',', decimal='.', headerlines=1, strip=True, onlystr=False, nullstr=None, nullfloat=None):
if isinstance(file, io.IOBase):
file.seek(0)
closefile = False
else:
file = open(file, 'r')
closefile = True
header = []
data = []
ncols = None
for i in range(headerlines):
row = file.readline()
cols = row.split(delimiter)
if not header:
ncols = len(cols)
for i in range(ncols):
header.append([])
data.append([])
for i in range(ncols):
if strip:
header[i].append(cols[i].strip())
else:
header[i].append(cols[i])
while True:
row = file.readline()
if not row.strip():
break
cols = row.split(delimiter)
for i in range(ncols):
if strip:
data[i].append(cols[i].strip())
else:
data[i].append(cols[i])
datalines = len(data[0])
if not onlystr:
for i in range(ncols):
asfloat = []
success = True
for j in range(datalines):
if data[i][j].strip() == nullstr:
asfloat.append(nullfloat)
continue
try:
asfloat.append(float(data[i][j]))
except:
success = False
break
if success:
data[i] = asfloat
if closefile:
file.close()
return header, data