Ramiro Peidro
Ramiro Peidro

Reputation: 25

CSV file content is being loaded with "quotes"

I need help to write and recover data from a csv file.

My parameter game is a tuple of 2 elements. Here's an example:

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

I need two functions, one to save the game an another one to recover it. This is what I've at the moment:

To save the game:

def save_game(game):
    with open ('file.csv', 'w') as f:
        csv_file = csv.writer(f)
        csv_file.writerow(game)

To recover the 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

When recovering the game, however, I'm getting something like this:

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

Is there any way to remove the quotes, so I can get a similar tuple like the one passed to my game parameter?

Thanks.

Upvotes: 1

Views: 59

Answers (1)

Talendar
Talendar

Reputation: 2087

As @BoarGules pointed out, you should probably use pickle in this case. Here's how you can do it:

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)

One of the nice things about this method is that it works with any picklable object, so even if you later decide to change the internal details of your game object, the two functions above should still work.

Upvotes: 1

Related Questions