使用Python在循环中读取多个txt文件

时间:2017-12-05 11:41:28

标签: python loops generator multiple-files

程序调用该函数并在循环中仅打开一次。你有什么解决方案可以让我一直在循环中调用函数吗? (我的意思是每个j)

def list_spectra(interpolated, txt):
    return (f for f in listdir(interpolated) if f.endswith("." + txt))

wl = []
fl = []
er = []

flux  = []
error = []

med_flux = []
med_err  = []

spectra_all = list_spectra("C:\\..my path here..\\interpolated","txt")
path = "C:\\..my path here..\\interpolated\\"

for j in range(0,len(wavelength)):
   for f in spectra_all:
        data = np.loadtxt(path+f)
        for ii in range(0,len(data)):

            wl = data[:,0]
            fl = data[:,1]
            er = data[:,2]    

            for i in range(0,len(wl)):
                if wl[i] == wavelength[j]:
                    flux.append(fl[i])
                    error.append(er[i])

    med_flux.append(np.median(flux))
    med_err.append(np.median(error))

1 个答案:

答案 0 :(得分:0)

你的意思是:

for j in range(0,len(wavelength)):
    spectra_all = list_spectra("C:\\..my path here..\\interpolated","txt")
    for f in spectra_all:
        data = np.loadtxt(path+f)
        # etc