如何用另一个输入数据重复另一个代码中的脚本

时间:2017-10-01 19:38:51

标签: multithreading python-2.7 popen repeat

我是python中的新手我写了一个代码,在这里我加载了一个txt文件,我得到了我的结果在另一个txt文件,我想重复这个代码的其他txt文件,我有他们所有在同一个文件夹。我想加载近300个txt文件并执行此操作,但我不知道该怎么做。感谢

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)

1 个答案:

答案 0 :(得分:0)

您需要定义一个将文件名作为参数的函数,并在程序的主要部分创建一个循环,在该循环中您可以找到要加载的所有文件,然后调用该函数,例如:

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)