【问题标题】:Read data from a txt file into 2D array python将txt文件中的数据读入二维数组python
【发布时间】:2018-07-14 18:11:38
【问题描述】:

我对 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] )。我看到很多人说要使用numpyscipy 和其他方法,但这让我更加困惑。

我正在寻找的输出是:

[[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)

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

【问题讨论】:

  • 你尝试过编码吗?
  • 我有,我正在网上找一些东西,并试图更好地理解。
  • 您应该在此处发布您的代码,以便我们修复它。
  • 请原谅我的格式
  • 编辑您的问题并将您的代码粘贴到那里。不要忘记格式化您的代码(例如使用 Ctrl+K)!

标签: python arrays parsing read-data


【解决方案1】:

您在一开始就错误地定义了 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)

【讨论】:

  • @user3600460 确保路径设置正确,例如可以使用print 函数调试它们
  • 上面的代码段可能有问题:with open(filename, 'r') as f: for line in f.readlines(): array2D.append(line.split(' ')) As I get a filename not found error.
【解决方案2】:

为了简单起见,我建议在与您希望阅读的文件相同的目录中运行 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

【讨论】:

  • 感谢您的意见!我将用我的数据测试这段代码。我喜欢添加的 try-except 文件 I/O 的方面。
猜你喜欢
  • 2014-04-06
  • 1970-01-01
  • 2012-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多