Knokkelgeddon Knokkelgeddon - 2 years ago 110
JSON Question

Save and load lists of strings in Python using JSON

I am trying to save lists (one per line) in a file like

w = meaningful_words
json.dump(w, outfile)

where w is a list of strings. Then I'm trying to load the lists, one at a time like

with open('text.txt', 'r') as file:
for line in file:
data = json.loads(

But I get the error

data = json.loads(
AttributeError: 'str' object has no attribute 'read'

Is there another way to do this? Found out JSON wood be easy to use but I can't get it to work.

Answer Source

You should change to just line:

with open('text.txt', 'r') as infile:
    for line in infile:
        data = json.loads(line)

File objects are iterators returning the next line if is called. The returned value is already a string and that's why you get the error message AttributeError: 'str' object has no attribute 'read'

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download