-1

我对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)

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

4

2 回答 2

2

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)
于 2018-07-14T18:37:38.723 回答
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
于 2018-07-15T23:13:48.747 回答