简体   繁体   中英

How to write multiple lists into a text file where each list is written into a new line?

I have two python lists:

a_list = [1, 2, 3]
b_list = [4, 5, 6]

How can I do the following:

create new text file ---> convert lists to json string ---> write lists into the file (each list should have its own line in the file) ---> open the file ---> read each line into a new variable and convert back from json string to python list?

I am stuck here:

import json

a_list = [1, 2, 3]
b_list = [4, 5, 6]

with open('test.txt', 'w') as f:
    f.write(json.dumps(a_list))
    f.write(json.dumps(b_list))

(The json string is written on the same line.)

Thanks

Using JSON

first you should put those lists into a dict

d = {
    "a" : a_list,
    "b" : b_list
}

Then you can dump it into .json file

json.dump(d,open("file.json","w"))

To read/load the files, you can use

d = json.load(open("file.json","r"))

which will return the original dictionary. ie,

{'a': [1, 2, 3], 'b': [4, 5, 6]}

Using Pickle

dumping

pickle.dump(a_list,open("b.ls","wb"))
pickle.dump(b_list,open("a.ls","wb"))

loading

pickle.load(open("a.ls","rb"))
pickle.load(open("b.ls","rb"))

fyi: I've never used pickle before :)

Comparison with json

  • There are fundamental differences between the pickle protocols and JSON (JavaScript Object Notation):

  • JSON is a text serialization format (it outputs unicode text, although most of the time it is then encoded to utf-8), while pickle is a binary serialization format;

  • JSON is human-readable, while pickle is not;

  • JSON is interoperable and widely used outside of the Python ecosystem, while pickle is Python-specific;

  • JSON, by default, can only represent a subset of the Python built-in types, and no custom classes; pickle can represent an extremely large number of Python types (many of them automatically, by clever usage of Python's introspection facilities; complex cases can be tackled by implementing specific object APIs);

  • Unlike pickle, deserializing untrusted JSON does not in itself create an arbitrary code execution vulnerability.

source (python docs)

tldr

  • pickle is smaller
  • json is faster
  • json is human readably (pickle file eg: �]q)
  • json is safer (not relavant in this case)

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