Pazzel
Pazzel

Reputation: 47

Can I translate a file into a list in python?

I am making a 2D platformer game in Python, and I need to store the maps in a file, then load them as a list. The file will contain something like this:

[[1,1,2,2,2,2,2,0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,2,2,1,0,0,0,0,1,1,0,0,2,2,0,0,0,0,0,1,2,1],
[0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1,2,0,0,0,0,0],
[2,0,0,0,0,0,1,1,0,2,2,2,0,1,1,0,0,0,0,1,0,0,0],
[0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,2,1,0,0,0,0,0,0]],

and it needs to make a list like this:

platforms = [[1,1,2,2,2,2,2,0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,2,2,1,0,0,0,0,1,1,0,0,2,2,0,0,0,0,0,1,2,1],
[0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1,2,0,0,0,0,0],
[2,0,0,0,0,0,1,1,0,2,2,2,0,1,1,0,0,0,0,1,0,0,0],
[0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,2,1,0,0,0,0,0,0]]

Is there any way I can do this?

Upvotes: 0

Views: 49

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155477

The json module should handle that format:

import json  # At top of file

with open(filename) as f:
    platforms = json.load(f)

That trailing comma may be a problem; if so, you can either strip if off (if there's nothing else in the file, just doing json.loads(f.read().rstrip("\r\n,")) will remove any trailing newlines and commas before the parsing), or perhaps use ast.literal_eval instead (that will safely, unlike eval, interpret it as a one-tuple wrapping the list, which you can extract and verify the singular nature of with the standard unpacking trick):

import ast  # At top of file

with open(filename) as f:
    [platforms] = ast.literal_eval(f.read())  # Brackets to unpack the one-tuple

Upvotes: 2

Related Questions