Knokkelgeddon Knokkelgeddon - 6 months ago 11
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)
outfile.write("\n");


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(line.read())


But I get the error

data = json.loads(line.read())
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

You should change line.read() 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 file.next() 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'

Comments