Created
November 3, 2021 18:50
-
-
Save felmoltor/f7b14a3efaab41b8399621c39765a404 to your computer and use it in GitHub Desktop.
Colorize CSV from pipes or files
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
#!/usr/bin/python3 | |
import csv | |
import random | |
import colorama | |
import sys,os | |
import tempfile | |
colors=list(vars(colorama.Fore).values()) | |
stream = None | |
file_name = None | |
is_file=False | |
# Read the file directly | |
if (len(sys.argv)==2 and os.path.exists(sys.argv[1])): | |
file_name = sys.argv[1] | |
is_file=True | |
# Create a file containing all the data coming form the pipe/stdin | |
else: | |
tmpfile=tempfile.NamedTemporaryFile(prefix="colorcsv",delete=True) | |
file_name=tmpfile.name | |
with open(file_name,"w") as tmp: | |
tmp.write(sys.stdin.read()) | |
# Continue with the normal processing of the file containing the CSV data | |
stream = open(file_name,"r") | |
sniffer=csv.Sniffer() | |
first_line = stream.readline() | |
dialect=sniffer.sniff(first_line) | |
stream.seek(0) | |
csvr = csv.reader(stream,dialect=dialect) | |
rown=0 | |
col_array=[] | |
max_fields=0 | |
for row in csvr: | |
if(max_fields<len(row)): | |
max_fields=len(row) | |
#Populate the color index array | |
prev_color=None | |
for n in range(max_fields): | |
# Bug: It could happen that the first row (header row) does not have the same number of fields as the rest of the rows, so | |
# we are going to pick the maximum number of columns of the the dataset | |
rndcol=colors[random.randint(0,len(colors)-1)] | |
while (rndcol == prev_color): | |
rndcol=colors[random.randint(0,len(colors)-1)] | |
col_array.append(rndcol) | |
prev_color=rndcol | |
stream.seek(0) | |
for row in csvr: | |
coln=0 | |
for col in row: | |
print(col_array[coln]+col,end="") | |
if (coln<len(row)-1): | |
print(dialect.delimiter,end="") | |
coln+=1 | |
print(colorama.Fore.RESET) | |
# Delete the temporal file | |
if (not is_file): | |
tmpfile.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment