Python - Writing to CSV files and for loops

11,015

Solution 1

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 })

Solution 2

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.

Share:
11,015
nikki_c
Author by

nikki_c

Updated on June 26, 2022

Comments

  • nikki_c
    nikki_c almost 2 years

    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.