how to delete a column in a python csv file

Asked

Viewed 2,072 times

0

How do I delete a column from a csv file? example:

nome;nota;idade
joao;10;12
maria;8;13
jose;6;8

to look like this:

nome;idade
joao;12
maria;13
jose;8

and how do I place a new column from that file to another file?

I’m still learning programming excuse if it’s something very simple for the forum

2 answers

6


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

0

  • 2

    don’t want to use it, just have to solve using it? this is a college exercise and haven’t learned about it yet

  • 1

    You can do it using standard python lib "csv," but if it’s a college exercise and you don’t want to learn new things, then go to humans :P

  • 2

    it is not a matter of learning new things or not, but my teacher asked us to use what he is teaching and not to skip matter, but thank you anyway.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.