简体   繁体   中英

User-readable file format for python list of lists

I'm considering using user-readable file format for my Python app. Right now I'm using pickle to store my data in binary. I'm not sure if XML or JSON is a way to go but basically my file contains list of lists that looks like this:

[1, 'the name of the set', [[1, 'data1', 'data2'],[2,'data3','data4']]

The list that hold the other lists containing the strings can have multiple items (even hundreds). Basically, I'd like to have something that has easy interface to convert it to/from python list and I need those integers to stay integers.

I'd use YAML here specifically PyYAML ; IHMO it's much nicer to read for humans!

Example: ( by hand )

foo:
    - 1
    - 2
    - 3

Nesting excluded from above example

Use: yaml.dump() and friends.

Demo:

>>> import yaml
>>> data = {"foo": [[1, 2, 3], [4, 5, 6]]}
>>> print yaml.dump(data)
foo:
- [1, 2, 3]
- [4, 5, 6]

NB: As JSON is a subset of YAML neither will preserve complex types; only basic types are supported; int , float , list , dict and str .

That's already literal JSON. JSON's probably the most popular format out there, and it's hard to argue with its legibility.

In [105]: my_list = [1, 'the name of the set', [[1, 'data1', 'data2'],[2,'data3','data4']]]
In [106]: my_list == json.loads(json.dumps(my_list))
Out[106]: True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM