Home > Software design >  How to Export "For" Loop to csv file?
How to Export "For" Loop to csv file?

Time:09-29

I have an example code:

fruits = 'apple', 'banana', 'kiwi'
veggies = 'corn','lettuce', 'spinach'

for x, y in zip(fruits,veggies):
    print(f' combo: {x}, {y}')

I am trying to export the output of this "for" loop to a CSV file, but have not succeeded with doing so. The output looks like this:

 combo: apple, corn
 combo: banana, lettuce
 combo: kiwi, spinach

Can I please get some guidance on how to export to a CSV?

CodePudding user response:

You must put a delimiter between the first column and the second. Specifically, you need to change each line to combo:, instead of just combo:. You can fix this by inserting a comma to your print statement:

print(f"combo:, {x}, {y}")

Finally, to export it to a CSV file, you need to get a file pointer and write to it. You could do it similar to the following (merge all the data to 1 string, then write it to a file), if you plan on making a new CSV file:

fruits = ['apple', 'banana', 'kiwi']
veggies = ['corn', 'lettuce', 'spinach']

# Make a new string to put all the data in
file_data = ""
for x, y in zip(fruits, veggies):
    file_data  = f"combo:, {x}, {y}\n"

# Make a new file
with open("test_file.csv", "w") as f:
    # Write to the file
    f.write(file_data)

CodePudding user response:

CSV fiels are simply txt files, so you can do something like this:

...
with open("shop.csv", "w") as fout: #<-- added this
    fout.write("fruits,veggies\n")  #<-- added this
    for x, y in zip(fruits,veggies):
        fout.write(f'{x},{y}\n')  #<-- added this

After running the code, you will find a new csv file called shop.csv having two columns: fruits and veggies

CodePudding user response:

You could save the output in a list and then write the ´list in a CSV file at the end of the for loop. Here's what I would do:

import csv

fruits = 'apple', 'banana', 'kiwi'
veggies = 'corn','lettuce', 'spinach'
combos = []

for x, y in zip(fruits,veggies):
    combos.append([x,y])

csv_file = "combos.csv"
try:
    with open(csv_file, 'w') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerows(combos)
except IOError:
    print("I/O error")
  • Related