-1

I saved a list with dict entries to a txt file.

When I try to read it back into python with

data = open("my_saved_data.txt","r")

I just get a huge string which looks like this:

[{key1:"value",key2:"value"},{key1:"value",key2:"value"},{key1:"value",key2:"value"}]

What's an easy way to get this back in the original format?

martineau
  • 119,623
  • 25
  • 170
  • 301
maltek
  • 23
  • 6
  • 2
    If you're trying to save dictionary data, I would suggest using the `json` module. Do you have control over the format that you're saving the dictionary in? – BrokenBenchmark Jan 22 '22 at 18:49
  • You _could_ use `ast.literal_eval` as well. But JSON is likely a better choice (parsers for it written in many programming languages). – BrokenBenchmark Jan 22 '22 at 18:50
  • You can use json package, which supports json object Serializing and Deserializing – Alex Jan 22 '22 at 18:52
  • @BrokenBenchmark I would rather not use `literal_eval` on the contents of a file. You can easily inject malicious code in the file. –  Jan 22 '22 at 19:00
  • `eval()` is the unsafe one, [`literal_eval()` is (probably) fine](https://stackoverflow.com/questions/4710247/python-3-are-there-any-known-security-holes-in-ast-literal-evalnode-or-string). – BrokenBenchmark Jan 22 '22 at 19:03
  • `data = open("my_saved_data.txt","r")` will **not** get you a string because afterwards `data` will simply be an open file object of some kind (i.e. not the contents of the file). – martineau Jan 22 '22 at 20:18
  • If you saved the list to the file using `json.dump()`, you would be able to read it back into its original format via `json.load()`. I think not saving it properly is the root cause of your problems. – martineau Jan 22 '22 at 20:26

1 Answers1

1

What you want is "Convert a String to JSON", but the type of your file content is not JSON, because the key in JSON should be enclosed in double quotes.

The correct content should like this:

[{"key1":"value","key2":"value"},{"key1":"value","key2":"value"},{"key1":"value","key2":"value"}]

then we can convert it to original format:

with open("my_saved_data.txt","r") as f:
    data = f.read()

print(data)
# '[{"key1":"value","key2":"value"},{"key1":"value","key2":"value"},{"key1":"value","key2":"value"}]'

import json
json.loads(data)
#[{'key1': 'value', 'key2': 'value'},
# {'key1': 'value', 'key2': 'value'},
# {'key1': 'value', 'key2': 'value'}]

Please make sure whether your key in str is enclosed or not, if not, we can make it enclosed by:

with open("my_saved_data.txt","r") as f:
    data = f.read()

data.replace('key1','"key1"').replace('key2','"key2"')
kerker
  • 38
  • 4