diff --git a/Pretty-CSV/README.md b/Pretty-CSV/README.md new file mode 100644 index 0000000..28fed11 --- /dev/null +++ b/Pretty-CSV/README.md @@ -0,0 +1,19 @@ +# Pretty CSV + +This script pretty-prints CSV input into a table output for easier readibility. The script reads from stdin and writes into stdout for pipe compatibility. + +## Examples +Read from local file +```sh +python3 pretty-csv.py < csv-file.csv +``` + +Read from `curl` +```sh +curl -fsSL https://people.sc.fsu.edu/~jburkardt/data/csv/cities.csv | python3 pretty-csv.py +``` + +Pipe to `less` for better navigation +```sh +python3 pretty-csv.py < long-csv-file.csv | less -S +``` diff --git a/Pretty-CSV/pretty-csv.py b/Pretty-CSV/pretty-csv.py new file mode 100644 index 0000000..74db008 --- /dev/null +++ b/Pretty-CSV/pretty-csv.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +import csv +import sys +from typing import Iterable, List + + +def main(): + content_lines = sys.stdin.buffer.readlines() + reader = csv.reader(line.decode('utf-8') for line in content_lines) + headers = next(reader) + print(create_table(reader, headers)) + + +def create_table(rows: Iterable[List[str]], headers: List[str]) -> str: + table = [headers] + column_lengths = [len(header) for header in headers] + for row in rows: + for i, text in enumerate(row): + column_length = column_lengths[i] + text_length = len(text) + if text_length > column_length: + column_lengths[i] = text_length + table.append(list(row)) + + result = [] + for row in table: + row_text = [] + for i, text in enumerate(row): + column_length = column_lengths[i] + row_text.append(space_pad(text, column_length)) + result.append(' '.join(row_text)) + return '\n'.join(result) + + +def space_pad(text: str, length: int) -> str: + temp = text + ''.join(' ' for _ in range(length)) + return temp[:length] + + +if __name__ == '__main__': + main() diff --git a/README.md b/README.md index 8816c24..e957538 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ So far, the following projects have been integrated to this repo: |[Yoda-speak Translator](https://github.com/hastagAB/Awesome-Python-Scripts/tree/master/speak_like_yoda)|[sonniki](https://github.com/sonniki) | |[Medium Article Downloader](https://github.com/hastagAB/Awesome-Python-Scripts/tree/master/medium_article_downloader)|[coolsonu39](https://github.com/coolsonu39)| |[Clean_up_photo](https://github.com/hastagAB/Awesome-Python-Scripts/tree/master/Clean_up_photo)|[sritanmay001](https://github.com/sritanmy001)| +|[Pretty CSV](https://github.com/Frizz925/Awesome-Python-Scripts/tree/pretty-csv/Pretty-CSV)|[Frizz925](https://github.com/Frizz925)| ## How to use : - Clone/Download the directory and navigate to each folder. Or...