70 lines
1.6 KiB
Python
Executable File
70 lines
1.6 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
import sys
|
|
import argparse
|
|
|
|
|
|
parser = argparse.ArgumentParser(
|
|
prog='CSV Transformer',
|
|
description='Creates a new CSV from another CSV file with all desired (renamed) columns in the desired order.'
|
|
)
|
|
parser.add_argument('file', help='The CSV file to edit.')
|
|
parser.add_argument('-c', '--columns', required=True, help='The columns to keep, rename (=) or to add (+) comma separated (Example: "Test,One=Two,+Three")')
|
|
parser.add_argument('-o', '--output', help='The name of the output file (if not specified the output will be written to the console)')
|
|
|
|
args = parser.parse_args()
|
|
|
|
columns_wanted = args.columns.split(',')
|
|
|
|
with open(args.file, 'r') as file:
|
|
csv = file.read()
|
|
|
|
lines = csv.split('\n')[:-1]
|
|
columns = lines[0].split(';')
|
|
new_head = []
|
|
column_to_column = []
|
|
|
|
for i,c in enumerate(columns_wanted):
|
|
if c.find('=') != -1:
|
|
old_name, new_name = c.split('=')
|
|
else:
|
|
old_name = c
|
|
new_name = c
|
|
|
|
new_head.append(new_name.replace('+', ''))
|
|
|
|
if old_name.startswith('+'):
|
|
index_old = None
|
|
else:
|
|
try:
|
|
index_old = columns.index(old_name)
|
|
except ValueError:
|
|
print('Error: The column %s does not exist!' % (old_name))
|
|
sys.exit(1)
|
|
|
|
|
|
column_to_column.append(index_old)
|
|
|
|
new_lines = []
|
|
|
|
for l in lines[1:]:
|
|
new_line = []
|
|
fields = l.split(';')
|
|
|
|
for i,c in enumerate(column_to_column):
|
|
if c is None:
|
|
new_line.append('')
|
|
else:
|
|
new_line.append(fields[c])
|
|
|
|
new_lines.append(';'.join(new_line))
|
|
|
|
output = ';'.join(new_head) + '\n'.join(new_lines)
|
|
|
|
if args.output is None:
|
|
print(output)
|
|
else:
|
|
with open(args.output, 'w') as file:
|
|
file.write(output)
|
|
|