简体   繁体   中英

Save files to a folder in python

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")

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM