In Python there is the native module csv
to work with CSV files. This defines the csv.DictReader
and csv.DictWriter
classes that make it easy to work with the named data.
See 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 context managers , both the original and the generated files are opened. The reader
object is defined which will be responsible for reading the input file and generating a dictionary for each line. The writer
object will be responsible for writing the new dictionary to the output file. Then you go through the input file, delete the desired column and write it to the output file.
You can easily abstract this for a function, which is given the name of the column you want to remove as a parameter, as well as fetch the columns of the original file from reader
, in this way you create a more versatile solution that will work for different files, with different columns, but that's left for you to do alone: D