Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) 

>Solution :

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
        ) 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading