Python - Writing to CSV files and for loops

nikki_c picture nikki_c · Aug 4, 2017 · Viewed 11.1k times · Source

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.

Answer

Rohan Piplani picture Rohan Piplani · Aug 4, 2017
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 })