John
John

Reputation: 37

How to name a file in a for loop separately from loop iterations

I have an array with size=(100,600,600) and want to split it into 4 (25,600,600) arrays and save them with names ldx1, ldx2, ldx3 and, ldx4 in n folders like below.

folder 1: ldx1, ldx2, ldx3 and, ldx4

folder 2: ldx1, ldx2, ldx3 and, ldx4

folder n: ldx1, ldx2, ldx3 and, ldx4

My code just saves the first file which is ldx1 in all folders. See my try below:


import numpy as np
import scipy.io

num_folders = 10
count=0

for i in range(num_folders):
   x=np.random.randint(0,1,size=(100,600,600))
   x_ = x[i:i+25,:]    
   count+=1
   scipy.io.savemat('fig/%d/ldx%d.mat' % (i,count),  mdict={'my_list':x_},do_compression=True) 

Upvotes: 0

Views: 36

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54698

You'll need two loops:

import numpy as np
import scipy.io

num_folders = 10

for i in range(num_folders):
   x = np.random.randint(0,1,size=(100,600,600))
   for j in range(4):
       scipy.io.savemat(
           'fig/%d/ldx%d.mat' % (i,j),
           mdict={'my_list':x[j*25:j*25+25,:,:]},
           do_compression=True
        ) 

Upvotes: 2

Related Questions