3

I'm currently trying to write to a CSV file in python, however I only want to print 'CurrentInv' every 60 iterations. For example

outfile = open("Pension.csv", 'w')
for k in range(1,Iterations+1):
    outfile.write(str( str(k) + ','))
    outfile.write(str(CurrentInv[k][0])+',')
    outfile.write(str(CurrentInv[k][60])+',')
    outfile.write(str(CurrentInv[k][120])+',')
    outfile.write(str(CurrentInv[k][180])+',')
    outfile.write(str(CurrentInv[k][240])+',')
    outfile.write(str(CurrentInv[k][300])+',')
    outfile.write(str(CurrentInv[k][360])+',')
    outfile.write(str('\n'))
outfile.close()

But I would like to obtain this in a loop. I have tried

 outfile = open("Pension5.csv", 'w')
 for k in range(1,Iterations+1):
     outfile.write(str( str(k) + ','))
     for i in range(0,Months+1):
        outfile.write(str(CurrentInv[k][i])+',')
        i=i+60
     outfile.write(str('\n'))
 outfile.close()`

However, this still prints all values for CurrentInv from 0 to Months instead of every 60 iterations. Any help would be appreciated!

5
  • 5
    Possible duplicate of For loop with custom steps in python Commented Oct 3, 2017 at 15:07
  • This is indeed a duplicate. Use range(0,Months+1,60). Commented Oct 3, 2017 at 15:12
  • I think the range he wants to modify is the other one @kabanus Commented Oct 3, 2017 at 15:14
  • @Adirio What? I see no problem :P Commented Oct 3, 2017 at 15:15
  • @kabanus * looks suspiciously to the new pen icon in the comment * - Guess I was wrong :P Commented Oct 4, 2017 at 10:44

1 Answer 1

1

Try the following:

with open("Pension5.csv", 'w') as outfile:
    for k in range(1, Iterations+1):
        outfile.write(str(str(k) + ','))
        for i in range(0, Months+1, 60):
            outfile.write(str(CurrentInv[k][i]) + ',')
        outfile.write(str('\n'))

It specifies a step of 60 for the range so that each iteration it adds 60 instead of 1. Months should be 360 in the example case. If you want Months to be 6 instead of 360 check the following:

with open("Pension5.csv", 'w') as outfile:
    for k in range(1, Iterations+1):
        outfile.write(str(str(k) + ','))
        for i in range(0, Months+1):
            outfile.write(str(CurrentInv[k][i*60]) + ',')
        outfile.write(str('\n'))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.