我需要能够从.txt文件中读取字符(数字)并在tkinter矩形坐标中使用它们。所以基本上我需要将这些数字存储在某个变量中才能使用它们。任何人
我试图这样做:
myfile = open('vystup.txt')
c = myfile.read(1)
工作正常,但我想阅读300,45这样的数字,而不仅仅是3,5,6等。
我的txt文件如下:
45 66 786 44
3 17 5 400
57 88 9 80 4
最好的解决方案是能够将每行的数字存储到不同的变量中。但我想这无论如何都应该很容易。
我也在stackoverflow上找到了这个:
a1 = []
a2 = []
a3 = []
a4 = []
with open('vystup.txt') as f:
for line in f:
data = line.split()
a1.append(int(data[0]))
a2.append(int(data[1]))
a3.append(int(data[2]))
a4.append(int(data[3]))
但这适用于列而非行。任何可以将此代码更改为行而不是列的人?
答案 0 :(得分:1)
正如doc所说:
要从文件中读取行,可以循环遍历文件对象。这个 内存高效,快速,并导致简单的代码
还有一个关于循环文件对象的例子。
假设您的输入是
45 66 786 44
3 17 5 400
57 88 9 80 4
此代码会将每个数字放入列表中。然后,您可以根据需要从这些列表中访问它们。
with open("numbers.txt") as f:
for line in f:
print (line.strip().split()) #strip removes newlines and split, does splitting.
#if you give split an argument it will split
#respect to that instead of spaces
>>>
['45', '66', '786', '44']
['3', '17', '5', '400']
['57', '88', '9', '80', '4']
答案 1 :(得分:0)
如果需要将这些值解析为整数,将这些数字保存为数组会很有用;让我们这样做:
var_array=[]
f=open('vystup.txt')
for line in f.readlines():
# read line, split it on spaces, and append them as integers to var_array
var_array.append(map(int,line.split()))
# now you have array of integers:
print var_array
>>> [[45, 66, 786, 44], [3, 17, 5, 400], [57, 88, 9, 80, 4]]
# having it, you can iterate through var_array
# selecting columns needed in your code;
# for example, get only first columns from your array:
for item in var_array:
print item[0]
>>> 45
>>> 3
>>> 56
等
当然我假设文件中的所有值都是整数。