-2

I want to save my python to json file, but the thing is, I need to name my json file's name as title's name.

code:

data={
    "Title" : title.text,
    "Registration": doctor.text,
    "Keywords": list2,
    "Article": list
}
#title.text="banana"

with open('title.text.json', 'w',encoding='UTF-8') as f:
    json.dump(data, f,ensure_ascii=False) 

The result I expected: Save it as banana.json

Edit: It works with this

with open('%s.json' % title_tag.text, 'w',encoding='UTF-8') as f:
    json.dump(data, f,ensure_ascii=False) 
Makiyo
  • 441
  • 5
  • 23

1 Answers1

1

you can use the following code to achieve this:

with open(title.text, 'w', encoding='UTF-8') as f:
    json.dump(data, f, ensure_ascii=False)
Ballack
  • 906
  • 6
  • 12
  • It's going to save it as html file instead of json file – Makiyo Oct 17 '17 at 02:52
  • you can use string.format to format your string.... ```with open('{file_name}.html'.format(file_name=title.text), 'w', encoding='UTF-8') as f``` In python3.6, you can achieve this by *with open(f"{title.text}.html", 'w', encoding='UTF'8') as f* – Ballack Oct 17 '17 at 02:52
  • with open('%s.json' % title_tag.text, 'w',encoding='UTF-8') as f: json.dump(data, f,ensure_ascii=False) – Makiyo Oct 17 '17 at 02:56