从txt文件读取数据到2D数组python中 [英] Read data from a txt file into 2D array python

查看:154
本文介绍了从txt文件读取数据到2D数组python中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对python还是很陌生,我想知道我是否可以解决我要解决的问题:

I'm fairly new to python and I would like to know if I could get some assistance with the problem I'm trying to solve:

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

I would like to design a loop to iterate over every file in the directory and place the data into a 2D array for every file. I have a large directory of .txt files that contain 22 lines of 2 numbers per line.

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

An example of how the files contents will be organized is:

# 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和其他方法,但这进一步使我感到困惑.

I would like to read the data separated by whitespace into the first two reference locations in the array(i.e. array = [x0][y0]) , and at the newline, write the following data into the next location of the array (i.e. array=[x1][y2]). I see a lot of people saying to use numpy, scipy, and other methods but that is confusing me further.

我正在寻找的输出是:

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

我对如何遍历目录中的文件并同时将它们放置到2D数组中有些困惑.到目前为止,我的代码是:

I'm bit stuck on how to iterate through the files in a directory and simultaneously place them into a 2D array. The code I have so far is:

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

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

print(array2D)

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

At the moment the above code does not work for two directories, but it does for one. Any help would be appreciated.

推荐答案

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

You are defining your array2D wrong at the beginning, that's not valid Python syntax. The following code should work:

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)

这篇关于从txt文件读取数据到2D数组python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆