![](/img/trans.png)
[英]What is the best way to save the comments collected from Facebook using Python?
[英]what is the best way to save tuples in python
我有一个函数返回一个包含数字,字符串和数组的元组。例如, (1, 2, 3, [[1,2,3],[4,5,6]], ['a','b','c'])
。 我需要运行我的功能100次并保存所有结果。 我想将每个结果保存为文本文件。 所以我可以有这样的100 * .txt文件:
my number1: 1
my number2: 2
my number3: 3
My array: [[1,2,3],[4,5,6]]
My Names: ['a','b','c']
如何编写python代码?
是否有更好的方法来保存结果,以便将来轻松重新访问数据?
是的,您可以import pickle
并使用pickle.dump()
和pickle.load()
来读取和写入文件。
以下是将其写入文件的方法:
data = (1, 2, 3, [[1,2,3],[4,5,6]], ['a','b','c'])
with open('data.pickle', 'wb') as f:
pickle.dump(data, f)
请阅读:
with open('data.pickle', 'rb') as f:
data = pickle.load(f)
如果您希望跨语言轻松重新访问数据,则可以使用JSON。
import json
data = (1, 2, 3, [[1,2,3],[4,5,6]], ['a','b','c'])
#save your data to a json file
with open('data01.json', 'w') as fjson:
json.dump(data, fjson)
#json file can easily be read using other languages as well
with open('data01.json', 'r') as fjson:
revis_data = json.load(fjson)
注意: revis_data
将转换为列表,不再是元组。 如果你希望它在重新加载后保持元组,只需做tuple(revis_data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.