From 43fdb709aa9dc563d4eda4490c2ff6dfd8b1104e Mon Sep 17 00:00:00 2001 From: mdaeron Date: Mon, 19 Oct 2020 19:05:31 +0200 Subject: [PATCH] Add D47crunch.read_csv() for convenience --- D47crunch/__init__.py | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/D47crunch/__init__.py b/D47crunch/__init__.py index a7db42e..838db88 100755 --- a/D47crunch/__init__.py +++ b/D47crunch/__init__.py @@ -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 Δ47 analyses, @@ -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: @@ -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: