Created
December 3, 2020 23:35
-
-
Save chasemc/9bea85e098f34016f65b4fbf7c84ec26 to your computer and use it in GitHub Desktop.
Print delimited files to terminal with https://github.com/willmcgugan/rich (Dependencies= pandas, rich)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import pathlib | |
from rich.console import Console | |
from rich.table import Table | |
from rich.table import Column | |
import pandas as pd | |
def make_rich(df, title="mytitle"): | |
table = Table(title=title) | |
for col in range(len(df.columns)): | |
table.add_column(str(col), style="green") | |
if len(df) > 2: | |
for row in range(0, 3): | |
table.add_row(*[str(i) for i in df.iloc[row, :].values.tolist()]) | |
else: | |
for row in range(len(df)): | |
table.add_row(*[str(i) for i in df.iloc[row, :].values.tolist()]) | |
console = Console() | |
console.print(table) | |
def find_files(dirpath, ext="tsv"): | |
a = [ | |
p | |
for p in pathlib.Path(dirpath).iterdir() | |
if p.is_file() and str(p).endswith(ext) | |
] | |
return a | |
def print_df(dirpath, ext, str_contains=None): | |
"""Pretty print table in terminal | |
Args: | |
dirpath (str): path containing tsvs | |
""" | |
if ext == "tsv": | |
sep = "\t" | |
elif ext == "csv": | |
sep = ".csv" | |
else: | |
raise # todo | |
files = find_files(dirpath) | |
# Convert PosixPath to string | |
files = [str(i) for i in files] | |
# If provided, filter files based on a word e.g. "header" | |
if str_contains != None: | |
files = list(filter(lambda x: str_contains in x, files)) | |
for i in files: | |
temp = pd.read_csv(i, sep=sep, header=None) | |
make_rich(temp, os.path.basename(i)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment