how to delete a column in a csv python file

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

How do I put a new column of this file into another file?

I'm still learning programming sorry if it's something very simple for the forum

    
asked by anonymous 22.11.2018 / 14:13

2 answers

7

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

    
22.11.2018 / 14:36
0

The simplest way to work with csv is by using Pandas. Take a look at this tutorial link

The code:

import pandas as pd

pd.read_csv('csv.csv', sep=';')\
    .drop(columns=['nota'])\
    .to_csv('csv_sem_nota.csv', sep=';', index=False)
    
22.11.2018 / 14:22