Last active
August 15, 2019 16:36
-
-
Save fish2000/5bf4bdf70e263d38436a8c5b89f70440 to your computer and use it in GitHub Desktop.
CSV data padding
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
# encoding: utf-8 | |
# Usage: `pad_csv(«uneven CSV data»)` -> «padded CSV data» | |
try: | |
from functools import reduce | |
except ImportError: | |
pass | |
segments = lambda line: len(line.split(',')) | |
max_segments = lambda csv_data: reduce( | |
lambda line_segments, next_line: max(line_segments, segments(next_line)), | |
csv_data.splitlines(), 0) | |
pad_line = lambda line, padding: line + ',' + ','.join('''""''' for idx in range(padding)) | |
pad_segments = lambda csv_data, padding: map( | |
lambda line: segments(line) < padding and pad_line(line, padding - segments(line)) or line, | |
csv_data.splitlines()) | |
pad_csv = lambda csv_data: '\n'.join(pad_segments(csv_data, max_segments(csv_data))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now a part of CLU: https://github.com/fish2000/CLU/blob/master/clu/csv.py