daven520
daven520

Reputation: 1

TypeError in CSV clean-up Script

I'm having trouble designing a script that will delete designated rows and columns from a CSV file. Here's my script so far:

import csv
with open ("E:\\CSULB Grad\\2016 Spring\\Geog 588\\Project\\ACS_14_5YR_B02001_Copy.csv","rb") as csvfile:
    reader=csv.reader(csvfile)
with open ("E:\\CSULB Grad\\2016 Spring\\Geog 588\\Project\\ACS_14_5YR_B02001_Copy.csv","ab+") as csvfile2:
    writer=csv.writer(csvfile2)
    for row in csvfile2:
        del row['HD02_VD01']
        writer.writerow(row)

Here's the traceback error I've been getting:

Traceback (most recent call last):
  File "C:\Python27\ArcGIS10.3\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript
    exec codeObject in __main__.__dict__
File "E:\CSULB Grad\2016 Spring\Geog 588\Project\Script2.py", line 7, in <module>
    del row['HD02_VD01']
TypeError: 'str' object does not support item deletion

Upvotes: 0

Views: 69

Answers (1)

ballade4op52
ballade4op52

Reputation: 2267

You can't modify a CSV file in-place as you iterate over it. Consider creating a new CSV file that writes only the columns that you require for each row in the original file.

For instance:

    with open(path,"wb") as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames = fieldNames)
        for row in csvfile2:
            writer.writerow({"Col1":row['...'],"Col2":row['...']})

Upvotes: 1

Related Questions