将txt文件中的数据读取到二维数组python

问题描述 投票:0回答:3

我对 python 相当陌生,我想知道我是否可以获得一些帮助来解决我试图解决的问题:

我想设计一个循环来迭代目录中的每个文件,并将每个文件的数据放入一个二维数组中。我有一个很大的 .txt 文件目录,其中包含 22 行,每行 2 个数字。

如何组织文件内容的示例是:

# Start of file_1.txt
1 2
3 4
5 6
7 8

# Start of file 2.txt
6 7
8 9
3 4
5 5

我想将由空格分隔的数据读取到数组中的前两个参考位置(即

array = [x0][y0]
),并在换行符处将以下数据写入数组的下一个位置(即
array=[x1][y2]
)。我看到很多人说使用
numpy
scipy
和其他方法,但这让我更加困惑。

我正在寻求的输出是:

[[1,2],[3,4],[5,6],[7,8], ...]

我对如何迭代目录中的文件并同时将它们放入二维数组感到有点困惑。到目前为止我的代码是:

import os
trainDir = 'training/'
testDir = 'testing/'
array2D = []

for filename in os.listdir(trainDir,testDir):
    if filename.endswith('.txt'):
        array2D.append(str(filename))

print(array2D)

目前,上述代码不适用于两个目录,但适用于一个目录。任何帮助将不胜感激。

python arrays parsing read-data
3个回答
3
投票

你一开始就定义了

array2D
错误,这不是有效的 Python 语法。以下代码应该可以工作:

import os

d = 'HERE YOU WRITE YOUR DIRECTORY'

array2D = []

for filename in os.listdir(d):
    if not filename.endswith('.pts'):
        continue

    with open(filename, 'r') as f:
        for line in f.readlines():
            array2D.append(line.split(' '))

print(array2D)

1
投票

为了简单起见,我建议在与您要读取的文件相同的目录中运行 python 脚本。否则,您将必须定义包含文件的目录的路径。

另外,我不确定是否只有您会使用这个程序,但在代码的 FileIO 部分周围定义一个 try- except 块可能是一个好主意,以防止程序在无法读取时崩溃出于任何原因从文件中删除。

下面的代码读取包含 python 脚本的目录中的所有文件,并创建文件内容的 2D 列表(此外,它以确保您拥有整数列表而不是字符串的方式显式重建 1D 列表):

import os

output_2d_list = []
current_working_directory = os.path.abspath('.')

# Iterates over all files contained within the same folder as the python script.
for filename in os.listdir(current_working_directory):
    if filename.endswith('.pts'):

        # Ensuring that if something goes wrong during read, that the program exits gracefully.
        try:
            with open(filename, 'r') as current_file:

                # Reads each line of the file, and creates a 1d list of each point: e.g. [1,2].
                for line in current_file.readlines():
                    point = line.split(' ')
                    x = int(point[0])
                    y = int(point[1])
                    point_as_array = [x, y]
                    output_2d_list.append(point_as_array)
        except IOError:
            print "Something went wrong when attempting to read file."

# For testing purposes to see the output of the script.
# In production, you would be working with output_2d_list as a variable instead.
print output_2d_list

0
投票

只需执行以下操作:

f = 打开(“file_1.txt”,“r”)

x = [line.split() for line in f]
f.close()

© www.soinside.com 2019 - 2024. All rights reserved.