如何使用numpy迭代.txt文件列表?

2024-05-08 03:46:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试迭代Python中的.txt文件列表。我想分别加载每个文件,创建一个数组,在每个数组的某一列中找到最大值,并将其附加到一个空列表中。每个文件都有三列,除了数字之外没有标题或其他内容。你知道吗

我的问题是开始迭代。我收到错误消息,如“没有这样的文件或目录”,然后显示列表中第一个.txt文件的名称。你知道吗

我使用os.listdir()来显示我正在使用的目录中的每个文件。我把它赋给变量filenamelist,我正试图迭代它。你知道吗

下面是我的一个迭代尝试:

for f in filenamelist:
    x, y, z = np.array(f)
    currentlist.append(max(z))

我希望它为每个文件创建一个数组,找到第三列的最大值(我已经分配给z),然后将其附加到一个空列表中,然后移到下一个文件。你知道吗

编辑:以下是我迄今为止编写的代码:

import os
import numpy as np
from glob import glob

path = 'C://Users//chand//06072019'
filenamelist = os.listdir(path)
currentlist = []
for f in filenamelist:
    file_array = np.fromfile(f, sep=",")
    z_column = file_array[:,2]
    max_z = z_column.max()
    currentlist.append(max_z)

编辑2:以下是我试图从中提取值的一个文件的片段:

0,           0.996,    0.031719
5.00E-08,    0.996,    0.018125
0.0000001,   0.996,    0.028125
1.50E-07,    0.996,    0.024063
0.0000002,   0.996,    0.023906
2.50E-07,    0.996,    0.02375
0.0000003,   0.996,    0.026406

每列长度为1000。我试图提取第三列的最大值并将其附加到空列表中。你知道吗


Tags: 文件inimport目录txt列表foros
1条回答
网友
1楼 · 发布于 2024-05-08 03:46:03

主要问题是np.array(filename)没有为您加载文件。根据文件的格式,像np.loadtxt()这样的东西可以起作用(参见docs)。你知道吗

编辑:如其他人所述,您的实现还有另一个问题。os.listdir()返回文件名的列表,但需要文件路径。您可以使用os.path.join()来获得所需的路径。你知道吗

下面是一个示例,说明了如何执行所需操作,但这实际上取决于文件格式。在这个例子中,我假设一个CSV(逗号分隔)文件。你知道吗

输入文件示例:

1,2,3
4,5,6

示例代码:

path = 'C://Users//chand//06072019'
filenames = os.listdir(path)
currentlist = []

for f in filenames:
    # get the full path of the filename
    filepath = os.path.join(path, f)
    # load the file
    file_array = np.loadtxt(filepath, delimiter=',')
    # get the whole third column
    z_column = file_array[:,2]
    # get the max of that column
    max_z = z_column.max()
    # add the max to our list
    currentlist.append(max_z)

相关问题 更多 >