-1

I'm trying to save the products.json and index.html files to the folder I create in this snippet. How do I do this?

It doesn't work as it stands. The files don't go inside of the directory, they just overwrite each other in the root directory as the script cycles through.

with open("products.json", "w") as write_file:
  json.dump({'items': all_products}, write_file)
  dirName = category_name.strip().lower().replace(' ', '-')
  try:
    os.mkdir(dirName)
    print("Directory ", dirName, " created")
  except FileExistsError:
    print("Directory ", dirName,  " already exists")
with open('cat_template.html') as file_:
  template = Template(file_.read())
  html = template.render(cat_dict)
  with open('index.html', 'w') as write_file:
    write_file.write(html)
print("Success" + single_url + " written to file")
Patrick
  • 374
  • 4
  • 21
  • Define "the best." What do you not like about the posted code? – DYZ Oct 26 '18 at 20:48
  • 1
    @DYZ I was unclear. It doesn't work as it stands. The files don't go inside of the directory, they just overwrite each other in the root directory as the script cycles through. – Patrick Oct 26 '18 at 20:52

1 Answers1

1

You can place them in the directory by changing these 2 lines:

with open(os.path.join(dirName, '') + "products.json", "w") as write_file:

with open(os.path.join(dirName, '') + 'index.html', 'w') as write_file:
user1394
  • 538
  • 1
  • 6
  • 17