Skip to content

Commit

Permalink
Add D47crunch.read_csv() for convenience
Browse files Browse the repository at this point in the history
  • Loading branch information
mdaeron committed Oct 19, 2020
1 parent caeb494 commit 43fdb70
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions D47crunch/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,28 @@ def w_avg(X, sX) :
return Xavg, sXavg


def read_csv(filename, sep = ''):
'''
Read contents of `filename` in csv format and return a list of dictionaries.
In the csv string, spaces before and after field separators (`','` by default)
are optional.
__Parameters__
+ `filename`: the csv file to read
+ `sep`: csv separator delimiting the fields. By default, use `,`, `;`, or `\t`,
whichever appers most often in the contents of `filename`.
'''
with open(filename) as fid:
txt = fid.read()

if sep == '':
sep = sorted(',;\t', key = lambda x: - txt.count(x))[0]
txt = [[x.strip() for x in l.split(sep)] for l in txt.splitlines() if l.strip()]
return [{k: smart_type(v) for k,v in zip(txt[0], l) if v} for l in txt[1:]]


class D47data(list):
'''
Store and process data for a large set of Δ<sub>47</sub> analyses,
Expand Down Expand Up @@ -518,7 +540,7 @@ def read(self, filename, sep = '', session = ''):
'''
Read file in csv format to load data into a `D47data` object.
In the csv file, spaces befor and after field separators (`','` by default)
In the csv file, spaces before and after field separators (`','` by default)
are optional. Each line corresponds to a single analysis.
The required fields are:
Expand Down Expand Up @@ -546,7 +568,7 @@ def input(self, txt, sep = '', session = ''):
'''
Read `txt` string in csv format to load analysis data into a `D47data` object.
In the csv string, spaces befor and after field separators (`','` by default)
In the csv string, spaces before and after field separators (`','` by default)
are optional. Each line corresponds to a single analysis.
The required fields are:
Expand Down

0 comments on commit 43fdb70

Please sign in to comment.