Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I want to save files for each result from the loop.

For example, I wrote the code but it only saves one file which is named "prac10.csv" which contains final results ([20, 12, 69, 31, 88, 40, 18, 71, 93, 19]).

epoch=10

randomlist=[]

for i in range (epoch):

    a=randint(1,100)

    randomlist.append(a)

    print(randomlist)

    with open('prac'+str(epoch)+'.csv','w') as f:

        f.write(str(randomlist))

However, I want to save the prac1.csv ~ prac10.csv with each loop results.

prac1.csv : [20]

prac2.csv : [20, 12]

prac3.csv : [20, 12, 69]

.....

prac10.csv : [20, 12, 69, 31, 88, 40, 18, 71, 93, 19]

How do I modify my code?

1 Answer

0 votes
by (36.8k points)

You are using the fixed variable file name 'prac'+str(epoch)+'.csv' and you are overwriting your file on each iterate, so you need to use a iteration variable for your filename (i in your example):

from random import randint

epoch = 10

randomlist = []

for i in range(epoch):

    a = randint(1, 100)

    randomlist.append(a)

    print(randomlist)

    with open('prac'+str(i+1)+'.csv', 'w') as f:

        f.write(str(randomlist))

Improve your knowledge in data science from scratch using Data science online courses 

If you wish to learn more about Python, visit the Python tutorial and Python course by Intellipaat.

Browse Categories

...