0

I have comma separated csv file like this:

A,B,C,D,E
1,4,5,6,7
9,52,12,0,7
1,5,15,6,9

I want to delete the content of the 4th column, but not the header.

the desired output is as following:

A,B,C,D,E
1,4,5,,4
9,52,12,,7
1,5,15,,9

how can i do it without using pandas?

Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61
Crankdat
  • 11
  • 5
  • Possible duplicate of [Deleting columns in a CSV with python](http://stackoverflow.com/questions/7588934/deleting-columns-in-a-csv-with-python) – roganjosh Nov 03 '16 at 21:50
  • just saw the duplicate. None of the answers handle the title, though. – Jean-François Fabre Nov 03 '16 at 21:52
  • @Jean-FrançoisFabre I'll agree with that but come on, at least the duplicate part could have been tried? There's no evidence of effort and the title of the question wouldn't help anyone else preserve the title row if that's what they struggled with. – roganjosh Nov 03 '16 at 21:53
  • Actually it's not a deletion of a column but rather a modification of the values. Maybe even easier, but not sure of the duplicate link (probably a duplicate of something else maybe) – Jean-François Fabre Nov 03 '16 at 21:58
  • @Jean-FrançoisFabre well I don't have the privilege to decide whether it's a dupe or not, so it's up to the higher powers to decide. But I don't consider filling a column with empty strings instead of deleting it that much of a leap. – roganjosh Nov 03 '16 at 22:00
  • you're right, it's easy. I just wanted to demonstrate how to read the title by iterating manually on the csv reader object, which avoid a dirty job using flags to tell if it's the first line or not. – Jean-François Fabre Nov 03 '16 at 22:03

1 Answers1

0

First open your file, attach it to a csv reader object.

Read the title by iterating manually on the csv.reader object (special case). Then open your output file, read the input rows, delete the 4th element and write back the rows in the output file:

import csv

with open("input.csv") as fr:
    cr = csv.reader(fr)
    title = next(cr)
    with open("output.csv","w") as fw:  # add ,newline='' for python 3
        cw = csv.writer(fw)
        cw.writerow(title)
        for row in cr:
            row[3]=""
            cw.writerow(row)
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219