Last active
December 15, 2015 13:08
-
-
Save Perlence/5264600 to your computer and use it in GitHub Desktop.
Set column number of CSV file to column number of first row moving latter items
This file contains 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 sys | |
import itertools | |
import csv | |
def grouper(n, iterable, fillvalue=None): | |
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" | |
args = [iter(iterable)] * n | |
return itertools.izip_longest(fillvalue=fillvalue, *args) | |
def chainfix(lines): | |
for line in lines: | |
fix = line | |
if not line[0]: | |
fix = line[1:] | |
for item in fix: | |
yield item | |
def skip_empty(items): | |
last = '' | |
for i in items: | |
if i.startswith(';') and i.endswith(';') and len(i) > 1: | |
yield i | |
elif i.startswith(';'): | |
nextitem = next(items) | |
if nextitem: | |
yield i + ';' | |
if nextitem != ';': | |
yield nextitem | |
else: | |
last = i | |
elif i == ';' and last: | |
yield last + ';' | |
last = '' | |
def fixlines(lines): | |
columns = tuple(s.strip(';') for s in next(lines, [])) | |
chained = (s.strip(';') for s in skip_empty(itertools.chain(*lines))) | |
# chained = chainfix(lines) | |
return itertools.chain([columns], grouper(len(columns), chained)) | |
def main(filename): | |
with open(filename) as fp: | |
lines = csv.reader(fp.readlines()) | |
fix = fixlines(lines) | |
writer = csv.writer(sys.stdout, lineterminator='\n') | |
writer.writerows(fix) | |
return 0 | |
if __name__ == '__main__': | |
try: | |
if len(sys.argv) > 1: | |
sys.exit(main(sys.argv[1])) | |
else: | |
sys.stderr.write('usage: csvfix.py CSVFILE\n') | |
except IOError as e: | |
sys.stderr.write(str(e) + '\n') | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment