我需要帮助从csv文件中写入和恢复数据。
我的参数game是一个包含2个元素的元组。下面是一个例子:
(((4, 0), (4, 1), (4, 2), (4, 3)), [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]])我需要两个函数,一个用于保存游戏,另一个用于恢复游戏。这就是我目前所拥有的:
要保存游戏,请执行以下操作:
def save_game(game):
with open ('file.csv', 'w') as f:
csv_file = csv.writer(f)
csv_file.writerow(game)要恢复游戏:
def recover_game():
with open ('file.csv', 'r') as f:
csv_file = csv.reader(f)
for line in csv_file:
game = line[0], line[1]
return game然而,当恢复游戏时,我得到了类似这样的东西:
('((4, 0), (4, 1), (4, 2), (4, 3))', '[[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]]')有没有办法去掉引号,这样我就可以得到一个类似于传递给game参数的元组?
谢谢。
发布于 2021-02-15 21:57:41
正如@BoarGules指出的那样,在这种情况下,你可能应该使用pickle。下面是你怎么做的:
import pickle
def save_game(game, out_pathname="./game.pkl"):
with open(out_pathname, "wb") as out_file:
pickle.dump(game, out_file, pickle.HIGHEST_PROTOCOL)
def recover_game(in_pathname="./game.pkl"):
with open(in_pathname, "rb") as in_file:
return pickle.load(in_file)这个方法的优点之一是它适用于任何可拾取的对象,所以即使您稍后决定更改game对象的内部细节,上面的两个函数也应该仍然有效。
https://stackoverflow.com/questions/66209156
复制相似问题