Created
August 4, 2020 20:43
-
-
Save fzembow/8e3cd149902497cb494ae5c80ae94b90 to your computer and use it in GitHub Desktop.
Prints the largest field lengths encountered in a CSV
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 csv | |
import sys | |
from collections import defaultdict | |
def print_max_field_lengths(fname): | |
""" | |
Prints the largest field lengths encountered in the csv | |
file in fname | |
""" | |
counts = defaultdict(int) | |
f = open(fname) | |
with f as csvfile: | |
reader = csv.DictReader(csvfile) | |
for row in reader: | |
for k, v in row.items(): | |
counts[k] = max(counts[k], len(v)) | |
for (k, count) in reversed(sorted(counts.items(), key=lambda x: x[1])): | |
print(count, k) | |
if __name__ == "__main__": | |
print_max_field_lengths(sys.argv[-1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment