【问题标题】:how to iterate over files in python and export several output files如何迭代python中的文件并导出多个输出文件
【发布时间】:2021-02-05 03:54:11
【问题描述】:

我有一个代码,我想把它放在一个 for 循环中。我想将一些存储为文件的数据输入到我的代码中,并根据每个输入自动生成输出。目前,我的代码仅适用于一个输入文件,因此提供了一个输出。我的输入文件被命名为model000.msh,但事实上我有一系列名称为model000.mshmodel001.msh 等的输入文件。在代码中,我正在对导入的文件进行一些计算,最后将其与另一个 numpy 数组 (ID) 生成的 numpy 数组 (my_data) 进行比较,该数组具有一列和数千行。 ID 数组是我要迭代的第二个变量。 ID 正在通过 np.concatenate 函数生成 my_data。我想使用ID 的每一列来制作my_data (my_data=np.concatenate((ID[:,iterator], gr), axis =1))。所以,我想遍历几个文件,然后从每个文件(extracted)中提取数组,然后按照循环从ID 的每一列生成my_data,并对my_dataextracted 进行计算最后以动态命名方式(changed_000changed_001等)导出每次迭代的结果。这是我的一个输入和一个 my_data 数组的代码(由一个只有一列的 ID 创建),但我想更改对多个输入文件和几个 my_data 数组的迭代,最后是几个输出:

from itertools import islice
with open('model000.msh') as lines:
        nodes = np.genfromtxt(islice(lines, 0, 1000))
with open('model000.msh', "r") as f:
    saved_lines = np.array([line.split() for line in f if len(line.split()) == 9])
saved_lines[saved_lines == ''] = 0.0
elem = saved_lines.astype(np.int)
# following lines extract some data from my file
extracted=np.c_[elem[:,:-4], nodes[elem[:,-4]-1, 1:], nodes[elem[:,-3]-1, 1:],nodes[elem[:,-2]-1, 1:], nodes[elem[:,-1]-1, 1:]]
…
extracted =np.concatenate((extracted, avs), axis =1) # each input file ('model000.msh') will make this numpy array
# another data set, stored as a numpy array is compared to the data extracted from the file
ID= np.array [[… ..., …, …]] # now, it is has one column, but it should have several columns and each iteration, one column will make a my_data array
my_data=np.concatenate((ID, gr), axis =1) # I think it should be something like my_data=np.concatenate((ID[:,iterator], gr), axis =1)
from scipy.spatial import distance
distances=distance.cdist(extracted [:,17:20],my_data[:,1:4])
ind_min_dis=np.argmin(distances, axis=1).reshape(-1,1)
z=np.array([])
for i in ind_min_dis:
    u=my_data[i,0]
    z=np.array([np.append(z,u)]).reshape(-1,1)
final_merged=np.concatenate((extracted,z), axis =1)
new_vol=final_merged[:,-1].reshape(-1,1)
new_elements=np.concatenate((elements,new_vol), axis =1)
new_elements[:,[4,-1]] = new_elements[:,[-1,4]]
# The next block is output block
chunk_size = 3
buffer = ""
i = 0
relavent_line = 0
with open('changed_00', 'a') as fout:
    with open('model000.msh', 'r') as fin:
        for line in fin:
            if len(line.split()) == 9:
                aux_string = ' '.join([str(num) for num in new_elements[relavent_line]])
                buffer += '%s\n' % aux_string
                relavent_line += 1
            else:
                buffer += line 
            i+=1
            if i == chunk_size:
                fout.write(buffer)
                i=0
                buffer = ""
    if buffer:
        fout.write(buffer)
        i=0
        buffer = ""

感谢您提前提供的任何帮助。

【问题讨论】:

    标签: python arrays numpy file


    【解决方案1】:

    我不太确定你的问题。但似乎您要求的是:

    for idx in range(10):
        with open('changed_{:0>2d}'.format(idx), 'a') as fout:
            with open('model0{:0>2d}.msh'.format(idx), 'r') as fin:
                #read something from fin...
                #calculate something...
                #write something to fout...
    

    如果是这样,您可以搜索 str.format() 以获取更多详细信息。

    【讨论】:

    • 亲爱的@Dipsy,感谢您的反馈。我想输入几个文件(model000.msh 等),提取一些数据(extracted)。再次从一个更大的数组 (ID) 创建一个数组 (my_data)。比较 my_dataextracted 并导出文件 (changed_00)。我的代码是针对单个输入执行此操作并导出一个输出,但我想遍历多个输入文件,然后导出多个文件。
    • 如果您对每个输入文件执行完全相同的操作,我认为我的回答可以解决您的问题。
    • 亲爱的@Dipsy,我很感激。你能详细说明一下吗?如何遍历多个输入文件并从ID 的每一列生成多个my_data?感谢您抽出时间。我是 python 新手,解决这些问题对我来说有点困难。
    • 至于如何遍历多个输入文件,我已经告诉过你使用forstr.format() 来打开不同的输入文件。至于你的dataID(很抱歉我对此感到困惑),我认为你应该简化你的问题并创建一个新的问题页面。我们不应该阅读您的整个代码并告诉您如何修复它。
    • 亲爱的@Dipsy,我非常感谢您提供的信息提示。我尝试使用您的提示和帮助来解决它。
    猜你喜欢
    • 1970-01-01
    • 2022-11-07
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 2021-06-29
    • 1970-01-01
    • 2020-01-24
    • 2021-12-02
    相关资源
    最近更新 更多