如何读取存储在Python文本文件中的整数列表数组?



我写了一个包含如下整数列表的文本文件

cords = [[385, 24], [695, 32], [1010, 106], [1122, 245]]
f = open('ref_points.txt', 'w')
f.write(str(cords))
f.close()

我想读回这个文本文件并得到整数列表。我知道当我们读取内容时,它是str,需要处理以存储在列表中。我想知道是否有更好更有效的方法来做这件事。

感谢

您可以使用pickle模块并将数据存储为二进制数据,这样您就不必执行任何类型转换。python已经自带了Pickle,所以你也不需要安装任何东西。

import pickle
coords = [[385, 24], [695, 32], [1010, 106], [1122, 245]]
f = open("points.bin", "wb")
pickle.dump(coords, f);
f.close();
# you can read it like this
f = open("points.bin", "wb")
coords = pickle.load(f) # here coords is a list so you do not have to convert anything
f.close()

正如@Marcin_Orlowski在评论中提到的那样,打开文件的更好方法是这样做:

with open("somefile.txt") as f:
# now you can use f for the file

这样你也不需要调用f.c close()。

最新更新