首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将txt文件中的数据读取到二维数组python中

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

Stack Overflow用户
提问于 2018-07-15 02:11:39
回答 2查看 13.6K关注 0票数 -1

我是python的新手,我想知道我是否可以得到一些帮助来解决我正在尝试解决的问题:

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

下面是文件内容组织方式的一个示例:

代码语言:javascript
复制
# 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])。我看到很多人建议使用numpyscipy和其他方法,但这让我更加困惑。

我正在寻找的输出是:

代码语言:javascript
复制
[[1,2],[3,4],[5,6],[7,8], ...]

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

代码语言:javascript
复制
import os
trainDir = 'training/'
testDir = 'testing/'
array2D = []

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

print(array2D)

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-15 02:37:39

你在一开始定义你的array2D是错误的,这不是有效的Python语法。下面的代码应该可以工作:

代码语言:javascript
复制
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)
票数 2
EN

Stack Overflow用户

发布于 2018-07-16 07:13:49

为了简单起见,我建议在您希望读取的文件所在的目录中运行python脚本。否则,您必须定义包含这些文件的目录的路径。

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

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

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51342162

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档