将文件保存到 python 中的文件夹

Save files to a folder in python

我正在尝试将 products.json 和 index.html 文件保存到我在此代码段中创建的文件夹中。我该怎么做?

它不能像现在这样工作。这些文件不会进入目录,它们只是在脚本循环时在根目录中相互覆盖。

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

您可以通过更改这两行将它们放在目录中:

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

with open(os.path.join(dirName, '') + 'index.html', 'w') as write_file: