Forum Archive

How to write a list into a file?

Kluesi

Hi

I have something like

x = [ [1, 2, 'Car'], [ [3, 4, 'House'], ... ]

Is there an easy way to write it to a file and read it from a file? E.g. something like

x.tostring() = ' [ [1, 2, 'Car'], [ [3, 4, 'House'], ... ]'

or something else.

Thanks Jens

dgelessus

For debugging you can simply print the list, which uses repr to convert it to a string. This is however not a good way to write a list to a file so you can load it again. For that you should use the json module to store your list as JSON. The basic JSON data types (null, true, false, numbers, strings, arrays, objects) are very similar to some of Python's built-in types (None, True, False, int/float, str/unicode, list, dict).

Webmaster4o

You could just use str(x).

dgelessus

@Webmaster4o That does the same thing as repr. The issue with that is that the only way to parse such a string back into a Python list is using eval, or if you're lucky ast.literal_eval. Using the json module is not much more complicated. Compare:

# Without JSON

import ast

# Store
with open("myfile.txt", "w") as f:
    f.write(repr(mylist))

# Load
with open("myfile.txt", "r") as f:
    mylist = ast.literal_eval(f.read())
# With JSON

import json

# Store
with open("myfile.json", "w") as f:
    json.dump(mylist, f)

# Load
with open("myfile.json", "r") as f:
    mylist = json.load(f)
Marque___

This script CANT be run on IOS, right?

dgelessus

Of course not, you can't run it on a PC either, because I never assigned anything to mylist. ;) This wasn't meant as a working script, I only wanted to point out the differences between using repr/eval and json to store a list in a file.