-2

My code looks like:

x=0
while (x<3):
    print('purple'),
    print('yellow'),
    print({x})
    x=x+1

I want it to log this data into a csv file named 'daffodils.csv'. How do I do this so that the iterations won't write over eachother?

For example, if I ran the program two times, my csv file will look like:

purple yellow 0
purple yellow 1
purple yellow 2
purple yellow 0
purple yellow 1
purple yellow 2

Thanks

g0dspl4y
  • 27
  • 1
  • 4

2 Answers2

1

Simply use,

with open('test.txt', 'a') as f:
    for x in range(3):
        s = 'purple yellow {}\n'.format(x)
        f.write(s)

Or use csv as you want,

import csv

with open('test.csv', 'a') as f:
    writer = csv.writer(f, delimiter=' ')
    for x in range(3):
        writer.writerow(['purple', 'yellow', x])
SparkAndShine
  • 17,001
  • 22
  • 90
  • 134
-1

Simply use:

t = open("daffodils.csv", "a+")
x=0
while (x<3):
    t.write('purple'),
    t.write('yellow'),
    t.write({x})
    t.write("\n")
    x=x+1
t.close()

The a opens the file in append mode, and the + creates it if it doesn't already exist.

clubby789
  • 2,543
  • 4
  • 16
  • 32