8

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

2 Answers 2

16

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])
Sign up to request clarification or add additional context in comments.

Comments

2

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(",") ]

1 Comment

This may hit problems if the last column of data happens to contain a comma. Using the CSV module should get around this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.