From 2264d26acc41da9d718eefbf99a3a0453affa914 Mon Sep 17 00:00:00 2001 From: Addison Klinke Date: Tue, 18 Jun 2019 11:54:33 -0600 Subject: [PATCH 1/2] add PrettyTable.to_csv() method --- prettytable/prettytable.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/prettytable/prettytable.py b/prettytable/prettytable.py index 02dab66..a8fd650 100644 --- a/prettytable/prettytable.py +++ b/prettytable/prettytable.py @@ -1004,6 +1004,26 @@ def clear(self): def copy(self): return copy.deepcopy(self) + def to_csv(self, filename, headers=True): + """Save PrettyTable results to a CSV file. + + Adapted from @AdamSmith https://stackoverflow.com/questions/32128226 + + Arguments: + + filename - filepath for the output CSV + headers - whether to include the header row in the CSV + """ + raw = self.get_string() + data = [tuple(filter(None, map(str.strip, splitline))) + for line in raw.splitlines() + for splitline in [line.split('|')] if len(splitline) > 1] + if not headers: + data = data[1:] + with open(filename, 'w') as f: + for d in data: + f.write('{}\n'.format(','.join(d))) + ############################## # MISC PRIVATE METHODS # ############################## From 9fd6c8dbbd4a8f0a8d19c1b07293701169e071aa Mon Sep 17 00:00:00 2001 From: Addison Klinke Date: Tue, 18 Jun 2019 12:21:49 -0600 Subject: [PATCH 2/2] ignore table title row (if present) when exporting to CSV --- prettytable/prettytable.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/prettytable/prettytable.py b/prettytable/prettytable.py index a8fd650..a63f5dd 100644 --- a/prettytable/prettytable.py +++ b/prettytable/prettytable.py @@ -1018,6 +1018,8 @@ def to_csv(self, filename, headers=True): data = [tuple(filter(None, map(str.strip, splitline))) for line in raw.splitlines() for splitline in [line.split('|')] if len(splitline) > 1] + if self.title is not None: + data = data[1:] if not headers: data = data[1:] with open(filename, 'w') as f: