如何通过在python中使用glob.glob从具有不同名称的多个输入文本文件中写入多个输出文本文件?

时间:2018-08-31 09:28:25

标签: python

我是python的初学者。我想从python中的50个输入文本文件中写入50个输出文件。 例如,我有输入文本文件,例如:

bottom_0cm_Box_0_B_90_wave_1.txt
bottom_0cm_Box_45_B_135_wave_1.txt
bottom_0cm_Box_90_B_180_wave_1.txt
...
top_0cm_Box_0_B_90_wave_1.txt
top_0cm_Box_45_B_135_wave_1.txt
top_0cm_Box_90_B_180_wave_1.txt
...

在一个文件中,我有1000个事件,我必须为每个事件做一些计算,因此我要遍历所有1000个事件。 我有以下代码:

file = glob.glob("/position/*.txt")
print file
print len(file)
for f in file:
    with open(f, 'rb') as input:
        all_lines = [line for line in input]
    x = np.arange(1,1025)   #x value is common for all the events
    Amplitude=list()
    for j in range(1,1000): 
        y2 = np.array(all_lines[1032*j+8:1032*(j+1)],dtype=float)
        x22 = list(x)
        y2_=list(y2)
        y22 = [((i / 4096)-0.5) for i in y2_] 
        min_y2 = min(y22)  # Find the maximum y2 value
        index_min_y2 = y22.index(min_y2)    #index for minimum of y2
        min_x2 = x[y22.index(min_y2)]
        print 'minimum x2', min_x2, 'minimum y2', min_y2
        Amplitude.append(round(min_y2, 2))
    with open ('bottom_0cm_Box_0_B_90_amplitude.txt', 'w') as fo:
       for d in Amplitude:
         fo.write(str(d) + '\n')

我要写:

  • 名称为输出文件bottom_0cm_Box_0_B_90_amplitude.txt的{​​{1}}的输入文本文件。
  • 输入文件名,其中输出文件名为bottom_0cm_Box_0_B_90_wave_1.txt的{​​{1}}

以此类推。

1 个答案:

答案 0 :(得分:0)

您可以将输入文件的名称分为基础名称和扩展名,用不同的后缀替换基础名称,将它们连接为全名,然后将基础名称与新的目录名称结合起来以获得完整路径名称。

添加:

import os.path

然后更改:

with open ('bottom_0cm_Box_0_B_90_amplitude.txt', 'w') as fo:

收件人:

basename, ext = os.path.splitext(os.path.basename(f))
basename = basename[:-len('wave_1')] + 'amplitude'
with open (os.path.join(new_dir, basename + ext), 'w') as fo:

此外,您不需要将所有结果保存到Amplitude列表中,因为之后要做的就是将其转储到文件中。相反,您应该将要追加到Amplitude的内容直接写到输出文件中以节省内存:

import os.path
import glob
file = glob.glob("/position/*.txt")
print file
print len(file)
for f in file:
    with open(f, 'rb') as input:
        all_lines = [line for line in input]
    x = np.arange(1,1025)   #x value is common for all the events
    basename, ext = os.path.splitext(os.path.basename(f))
    basename = basename[:-len('wave_1')] + 'amplitude'
    with open(os.path.join(new_dir, basename + ext), 'w') as fo:
        for j in range(1,1000):
            y2 = np.array(all_lines[1032*j+8:1032*(j+1)],dtype=float)
            x22 = list(x)
            y2_=list(y2)
            y22 = [((i / 4096)-0.5) for i in y2_]
            min_y2 = min(y22)  # Find the maximum y2 value
            index_min_y2 = y22.index(min_y2)    #index for minimum of y2
            min_x2 = x[y22.index(min_y2)]
            print 'minimum x2', min_x2, 'minimum y2', min_y2
            fo.write(str(round(min_y2, 2)) + '\n')