将 txt 文件中的数据读入二维数组 python
Read data from a txt file into 2D array python
我是 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)
目前上面的代码不适用于两个目录,但它适用于一个目录。任何帮助,将不胜感激。
您一开始就定义了 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)
为了简单起见,我建议 运行 将 python 脚本与您希望阅读的文件放在同一目录中。否则,您将必须定义包含文件的目录的路径。
此外,我不确定是否只有您会使用这个程序,但最好在代码的 FileIO 部分周围定义一个 try-except 块,以防止程序崩溃由于任何原因无法从文件中读取。
下面的代码读取包含 python 脚本的目录中的所有文件并创建文件内容的二维列表(此外,它以确保您拥有整数列表而不是字符串列表):
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
我是 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)
目前上面的代码不适用于两个目录,但它适用于一个目录。任何帮助,将不胜感激。
您一开始就定义了 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)
为了简单起见,我建议 运行 将 python 脚本与您希望阅读的文件放在同一目录中。否则,您将必须定义包含文件的目录的路径。
此外,我不确定是否只有您会使用这个程序,但最好在代码的 FileIO 部分周围定义一个 try-except 块,以防止程序崩溃由于任何原因无法从文件中读取。
下面的代码读取包含 python 脚本的目录中的所有文件并创建文件内容的二维列表(此外,它以确保您拥有整数列表而不是字符串列表):
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