简体   繁体   English

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

[英]How to read array of integer list stored in text file in Python?

I wrote a text file that contains list of integers like below我写了一个包含整数列表的文本文件,如下所示

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

I want to read back this text file and get the list of integers.我想读回这个文本文件并获取整数列表。 I know when we read contents, it is str, and need processing to store in list.我知道当我们读取内容时,它是 str,需要处理以存储在列表中。 I would like to know if there is any better and efficient way of doing it.我想知道是否有更好、更有效的方法来做到这一点。

Thanks谢谢

You can use the pickle module and store the data as binary data, this way you have to not perform any type conversions.您可以使用 pickle 模块并将数据存储为二进制数据,这样您就不必执行任何类型转换。 pickle already comes with python so you do not have to install anything either. pickle 已经带有 python 所以你也不需要安装任何东西。

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()

also as @Marcin_Orlowski mentioned in the comments, a better way to open files will be to do so:也正如@Marcin_Orlowski 在评论中提到的那样,打开文件的更好方法是这样做:

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

this way you dont have to call f.close() either.这样你也不必调用 f.close() 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM