Home > Back-end >  python - storing lists as text and converting back again without separation issues
python - storing lists as text and converting back again without separation issues

Time:01-29

what I want is to read and write list of texts to a txt file without separation issues


here's a example from browsers

  • if I search 'cats dogs', the link becomes 'cats dogs'
  • if I search 'cats dogs', the link becomes 'cats+dogs'
  • if I search 'cats+dogs', the link becomes 'cats%2Bdogs'

it is little ahead of my skills rn (:

lis = ['abc', 'def', '123']
def list_to_text(lis):
    pass

def text_to_list(text):
    pass

CodePudding user response:

It looks like you want to serialize the list into a string, store it, then deserialize that string. You likely want to use the json module, as your example only uses primitives in your list. Like this:

import json

lis = ['abc', 'def', '123']
serialized = json.dumps(lis)
# store `serialized` somewhere, or to a file with json.dump()

out = json.loads(serialized)  # or use json.load() if reading from a file
print(out)

If you need to store data that JSON does not support, try using pickle instead (though, note that you should only pickle trusted data, not user input). It has the same interface as the json module. Like this:

import pickle

lis = ['abc', 'def', '123']
serialized = pickle.dumps(lis)
# store `serialized` somewhere, or to a file with json.dump()

out = pickle.loads(serialized)  # or use json.load() if reading from a file
print(out)
  • Related