0

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.

1
  • use dumps not loads Commented May 31, 2016 at 10:10

1 Answer 1

1

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'

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Can you tell me why?
@Knokkelgeddon just edited my answer to include some explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.