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(',')
withopen(args.file,'r')asfile:
csv=file.read()
lines=csv.split('\n')[:-1]
columns=lines[0].split(';')
new_head=[]
column_to_column=[]
fori,cinenumerate(columns_wanted):
ifc.find('=')!=-1:
old_name,new_name=c.split('=')
else:
old_name=c
new_name=c
new_head.append(new_name.replace('+',''))
ifold_name.startswith('+'):
index_old=None
else:
try:
index_old=columns.index(old_name)
exceptValueError:
print('Error: The column %s does not exist!'%(old_name))