如何在Python中从文本文件中读取行列数据的值
你好,我有一个文本文件,里面有很多行和列的数字数据,下面是一个例子。
21,73,12,73,82,10
17,28,19,21,39,11
17,39,19,21,3,91
12,73,17,32,18,31
31,29,31,92,12,32
28,31,83,21,93,20
我想做的是能够单独读取每个值,同时也能知道它所在的行和列的编号。比如,行0列2的值是12。
然后我想把行、列和这个值写入一个变量里,比如 = i,j,d。
我可以把这些数据读入一个数组,按行分割,行数和列数也能算出来,但我就是不知道怎么单独提取每个值。
下面是我认为可以工作的代码,这段代码是根据伪代码写的,其中“i”和“j”代表行和列的编号,“b”是上面表格中与此相关的数据,然后会进行循环。
i = 0
for a in array:
j = 0
for b in array:
if b != 0:
write.code(i,j,b)
j+=1
i+=1
1 个回答
0
根据你最初的代码,这样做应该可以解决问题。
# using with is the safest way to open files
with open(file_name, "r") as file:
# enumerate allows you to iterate through the list with an index and an object
for row_index, row in enumerate(file):
# split allows you to break a string apart with a string key
for col_index, value in enumerate(row.split(",")):
#convert value from string to int
# strip removes spaces newlines and other pesky characters
b = int(value.strip())
if b != 0:
g.add_edge(row_index,col_index, b)
如果你只是想把它变成一个数组,可以用列表推导式来简化这个过程。
with open(file_name, "r") as file:
my_array = [ [int(value.strip()) for value in row.split(",")] for row in file]