Search code examples
multithreadingpython-2.7popenrepeat

how to repeat a script in another code with another input data


I am newbie in python I wrote a code that in this I load a txt file and I get my result in another txt file, and I want to repeat this code for other txt files that I have all of them in same folder. I want to load almost 300 txt files and do this, but I don't know how do that. thanks

dat = np.loadtxt('test1.txt')
x = dat[:, 0]
y = dat[:, 2]
peak = LorentzianModel()
constant = ConstantModel()
pars = peak.guess(y, x=x)
pars.update( constant.make_params())
pars['c'].set(1.04066)
mod = peak + constant
out=mod.fit(y, pars, x=x)
comps = out.eval_components(x=x)
writer = (out.fit_report(min_correl=0.25))
path = '/Users/dellcity/Desktop/'
filename = 'output.txt'
with open(path + filename, 'wt') as f:
    f.write(writer)

Solution

  • you need to define a function that gets the filename as a parameter and in the main part of your programm create a loop in which you find all files which you want to load and then call the function, e.g.:

    import os
    
    def myFunction(filename):
        dat = np.loadtxt(filename)
        x = dat[:, 0]
        y = dat[:, 2]
        peak = LorentzianModel()
        constant = ConstantModel()
        pars = peak.guess(y, x=x) 
        pars.update( constant.make_params())
        pars['c'].set(1.04066)
        mod = peak + constant
        out=mod.fit(y, pars, x=x)
        comps = out.eval_components(x=x)
        writer = (out.fit_report(min_correl=0.25))
        path = '/Users/dellcity/Desktop/'
        filename = 'output.txt'
        # open in mode a = append
        with open(path + filename, 'at') as f:
           f.write(writer)    
    
    # the parameter of os.listdir is the path to your file, 
    # change to the path of your data files
    for filename in os.listdir('.'):
        if filename.endswith(".txt"):
            myFunction(filename)