Сохраните файлы в папку в Python - PullRequest
0 голосов
/ 26 октября 2018

Я пытаюсь сохранить файлы 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")

1 Ответ

0 голосов
/ 27 октября 2018

Вы можете поместить их в каталог, изменив эти 2 строки:

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

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