Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete or remove last column in CSV file using Python

Tags:

python

csv

I have a CSV file with 5 columns. Using Python, how can I delete the last column (header5 in the example)? Is there an easy way I'm missing, or do I have to loop through all rows in the CSV and remove each value from the last column (which could still leave me with the undesired preceding comma)?

I'm not seeing anything related to this in the CSV module or elsewhere on the interwebs, so any help is much appreciated.

header1,header2,header3,header4,header5
value1,value2,value3,value4,value5
value1,value2,value3,value4,value5
like image 540
Gady Avatar asked Aug 30 '11 15:08

Gady


People also ask

How do I remove a column from a CSV file?

Question Detail Do select [column_names] from [table] store this in a CSV file. Now you will have only required columns in the output CSV. You can use alter SQL command to delete a column but I never tried it. Another option is open the CSV using excel command and use delete column to delete the entire column.

How do I read a specific column in a CSV file in Python?

In this method we will import the csv library and open the file in reading mode, then we will use the DictReader() function to read the data of the CSV file. This function is like a regular reader, but it maps the information to a dictionary whose keys are given by the column names and all the values as keys.


2 Answers

Use the csv module. When writing out a row, use row[:-1] to chop off the last item:

import csv

with open(filename,"r") as fin:
    with open(outname,"w") as fout:
        writer=csv.writer(fout)
        for row in csv.reader(fin):
            writer.writerow(row[:-1])
like image 154
unutbu Avatar answered Nov 16 '22 23:11

unutbu


Even if you don't use CSV module, the logical and sane way is to read the file row by row, split them on comma, and print out item 1 through 4 with a join. eg

for line in open("file"):
    print ','.join( line.split(",")[:-1] )

Or just by simple string indexing

for line in open("file"):
    print line[ : line.rindex(",") ]
like image 29
ghostdog74 Avatar answered Nov 17 '22 00:11

ghostdog74