Stix
Stix

Reputation: 15

Write multiple rows from several lists into a CSV

I am trying to extract data from a csv, format it a little and then write it either back to the same csv or to a new one (no preference). there are around 1500 rows in the original csv and I can't get it written back in the same way.

my code is

OBJECTID = []
KKOD = []
KATEGORI = []
SHAPE_Length = []

with open(tempcsv, 'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        OBJECTID.append(row.get('OBJECTID'))
        KKOD.append(row.get('KKOD'))
        KATEGORI.append(row.get('KATEGORI'))
        SHAPE_Length.append(row.get('SHAPE_Length'))

#Puts data in lower case
KATEGORI = [kategori.lower() for kategori in KATEGORI]
#finds all non standard characters
catstrip = ([s.strip('¤') for s in KATEGORI]) 
#delets all non standard characters
categories = ([s.replace('¤', '') for s in KATEGORI])
print(categories)

with open('mycsv.csv', 'w', newline='') as k:
    fieldnames = ['OBJECTID', 'KKOD','KATEGORI','SHAPE_Length']
    writer = csv.DictWriter(k, fieldnames=fieldnames)
    writer.writeheader()
    for i in tempcsv(OBJECTID):
        writer.writerow({"OBJECTID" : OBJECTID, "KKOD" : KKOD, "KATEGORI" : categories, "SHAPE_Length" : SHAPE_Length})

Object ID is the number of rows I want to use in the iterator but it is returning the error of TypeError: 'str' object is not callable.

if I take the iterator away it writes all outputs to one row.

Upvotes: 1

Views: 24

Answers (1)

hackinteachk
hackinteachk

Reputation: 313

From what I understand from the given code you might want last section to be like this:

with open('mycsv.csv', 'w', newline='') as k:
    fieldnames = ['OBJECTID', 'KKOD','KATEGORI','SHAPE_Length']
    writer = csv.DictWriter(k, fieldnames=fieldnames)
    writer.writeheader()
    for i in range(len(OBJECTID)): # <- starting this line
        writer.writerow({"OBJECTID" : OBJECTID[i], "KKOD" : KKOD[i], "KATEGORI" : categories[i], "SHAPE_Length" : SHAPE_Length[i]})

More explanation

noted from this remark : "if I take the iterator away it writes all outputs to one row.", that's because you do writer.writerow({"OBJECTID" : OBJECTID, "KKOD" : KKOD, "KATEGORI" : categories, "SHAPE_Length" : SHAPE_Length}), recall that you define each value above as [] which is a list, so you basically write all items in to 1 line.

you might want to check out the official documentation for more information and example :) https://docs.python.org/3/library/csv.html#writer-objects

Upvotes: 1

Related Questions