In Python there is the native module csv
to work with CSV files. This defines the classes csv.DictReader
and csv.DictWriter
that facilitate working with the named data.
Take an example:
import csv
with open('original.csv') as stream, \
open('resultado.csv', 'w') as output:
reader = csv.DictReader(stream, delimiter=';')
writer = csv.DictWriter(output, delimiter=';', fieldnames=['nome', 'idade'])
writer.writeheader()
for row in reader:
del row['nota']
writer.writerow(row)
With contextual managers the two files are opened, the original and the one that will be generated. The object is defined reader
which will be responsible for reading the input file and generating a dictionary for each line. The object writer
will be responsible for writing the new dictionary in the output file. You scroll through the input file, delete the desired column and write it to the output file.
You can easily abstract this to a function, which takes as a parameter the name of the column you want to remove, as well as fetch the columns from the original file from the reader
, this way you create a more versatile solution that will work for different files, with different columns, but this I leave for you to do alone :D
thank you very much!
– Arthur Carvalho