Home > other >  Running a code multiple times and saving data after every run in Python
Running a code multiple times and saving data after every run in Python

Time:09-14

I am running this code 10 times. After every run, I want to create a folder n where n is the number of the run and save the data with file name Inv_Radius_220_47_53ND.csv in that folder. For instance, after first run, folder 1 is created and then Inv_Radius_220_47_53ND.csv is saved. Then after second run, folder 2 is created and Inv_Radius_220_47_53ND.csv is saved in this folder. Just for info, the file name should be the same across all folders, only different folder names.

def function():
    from scipy.stats import truncnorm
    import numpy as np
    import csv 

    a, b = 47.0,53.0
    Nodes=12  #reshape into
    r = (1e-6)*np.linspace(truncnorm.ppf(0.001, a, b),truncnorm.ppf(1.0, a, b), Nodes)
    print("r =",[r])

    sort_r = np.sort(r); 
    r1=sort_r[::-1]
    print("r1 =",[r1])
    #print("r =",[r])

    r1=r1.reshape(1,Nodes)
    print("r1 shape =",[r1])

    r2 = r.copy()

   
    np.random.shuffle(r2.ravel()[1:])
    print("r2 =",[r2])    

    r2=r2.reshape(1,Nodes)
    print("r2 =",[r2])                          #actual radius values in mu(m)

    maximum = r2.max()
    indice1 = np.where(r2 == maximum)
    # minimmum = r2.min()
    # indice2 = np.where(r2 == minimum)
    r2[indice1] = r2[0][0]
    r2[0][0] = maximum
    #print(r2)
    r2[0][Nodes-1] = maximum  # 0.01*maximum
    #print(r2)
    print("r2 with max at (0,0)=",[r2])

    with open('Inv_Radius_220_47_53ND.csv', 'w ') as f: 
        inv_r=1/r2
        print("inv_r =",[inv_r])
        writer = csv.writer(f)
        writer.writerows(inv_r)
     

    mean=np.mean(r)
    print("Mean =",mean)
    var=np.var(r)
    print("var =",var)
    std=np.std(r)
    print("std =",std)

for x in range(10):
    function()

CodePudding user response:

I truncated the parts that weren't important to the question but is this what you're looking for?

import os
from scipy.stats import truncnorm
import numpy as np
import csv


def function(run):
    ...

    # Create the folder with the number of the run as name
    # Add 1 to run so the first run is 1 and not 0
    parent_folder = str(run   1)
    os.mkdir(parent_folder)
    # Join the parent folder with the filepath: 0/Inv_Radius_220_47_53ND.csv
    with open(os.path.join(parent_folder, 'Inv_Radius_220_47_53ND.csv'), 'w ') as f:
        inv_r = 1 / r2
        print("inv_r =", [inv_r])
        writer = csv.writer(f)
        writer.writerows(inv_r)

    ...


for x in range(10):
    function(x)
  • Related