0

I'm writing a script that works with certain vocabulary. As a part of it, I want to store the incoming json data of a word in a file. The following code works only for one word at a time. But it will replace the data.json file every time with the json information of the new word.

with open('data.json', 'w') as outfile:
    json.dump(data, outfile)

What I'm trying to achieve is: I would like to store the json of each file separately. For eg: if the word is "internet", then I want the file to export internet.json and if the word is "persistence," then i want the json to store persistence.json

I tried the below, but it throws a syntax error:.

with open(word||'.json', 'w') as outfile:
    json.dump(data, outfile)

I'm new to Python (using Python3) and I'm working on a pet-project. So, it would be a great support if you can help me in achieving this. Thanks in advance.

LearneR
  • 2,351
  • 3
  • 26
  • 50
  • `||` is not a "concat operation", it's a syntax error. Python has the `|` operator which is binary-or, but there's no `||` operator. No idea where you got that from. – Aran-Fey Mar 17 '19 at 07:23
  • I'm afraid I got it from SQL. Anyway, as the other person pointed that it's a duplicate question, I was looking at the answer of it. And I tried: `with open('word(%s)'.json' % word, w) as outfile: json.dump(data, outfile)` But this still shows a syntax error: `name 'w' is not defined`. Can you please tell me where I'm going wrong? – LearneR Mar 17 '19 at 07:26
  • You need quotes around the `w` - like in the code in your question... – Aran-Fey Mar 17 '19 at 07:31
  • Also, ignore the first answer in the linked duplicate question. The 2nd answer is much better. – Aran-Fey Mar 17 '19 at 07:32
  • 1
    @Aran-Fey Done. It works now. `with open('%s.json' % word, 'w') as outfile: json.dump(data, outfile)` Thank you very much for correcting me. – LearneR Mar 17 '19 at 07:35

0 Answers0