nikki_c
nikki_c

Reputation: 117

Python - Writing to CSV files and for loops

EDIT The approved answer is correct and all of my data appears in the file, however since it is looping through and writing each piece of information to a new row, the data is unorganized and appears in a cascading pattern. At this point it is just a formatting problem. Anyone experience a similar issue?

I have a for loop in which I am defining multiple variables. I need to print the values within those variables to a CSV without writing over the rows over and over again. I know the solution to this involves putting the "with open" statement outside of the for loop, but then python does not recognize my variables anymore.

I think another part of the solution is to append the data within the variables so you can call it outside of the for loop, but I'm not sure how to do this for my case.

Example:

for item in my_list:

    info  = inspect.getmembers(item)
    name = info[0]

import csv

with open("sample.csv", "w") as csvFile:
    fieldnames = ['Item Name']
    writer = csv.DictWriter(csvFile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'Item Name': name })
csvFile.close()

In this example, the variable "name" cannot be defined because it is defined within the for loop.

Upvotes: 3

Views: 13797

Answers (2)

Rohan Piplani
Rohan Piplani

Reputation: 232

import csv
with open("sample.csv", "w") as csvFile:
    fieldnames = ['Item Name']
    writer = csv.DictWriter(csvFile, fieldnames=fieldnames)
    writer.writeheader()

    for item in list:
        info  = inspect.getmembers(item)
        name = info[0]

        writer.writerow({'Item Name': name })

Upvotes: 7

RagingRoosevelt
RagingRoosevelt

Reputation: 2164

Put the with before your loop so that you can write the values to the file from within your for loop:

import csv
with open('sample.csv', 'w') as csvFile:
    fieldnames = ['Item Name']
    writer = csv.DictWriter(csvFile, fieldnames=fieldnames)
    writer.writeheader()

    for item in list:
        # get the data you want from item
        info  = inspect.getmembers(item)
        name = info[0]

        # write the data to the file
        writer.writerow({'Item Name': name })

NOTE (since I don't have sufficient reputation to comment yet): csvFile.close() found in Rohan's answer is not necessary since that is handled by the with statement. Also, per PEP8, he should use 2 spaces rather than 4 for indentations.

Upvotes: 3

Related Questions