首页 > 解决方案 > 如何在 python 中使用 glob.glob 从具有不同名称的多个输入文本文件中写入多个输出文本文件?

问题描述

我是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')

我想写:

等等。

标签: python

解决方案


您可以将输入文件的名称拆分为基本名称和扩展名,用不同的后缀替换基本名称,将它们连接成一个全名,然后将基本名称与一个新的目录名连接起来作为一个完整的路径名。

添加:

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')

推荐阅读