我正在尝试将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")
答案 0 :(得分:1)
您可以通过更改以下两行将它们放置在目录中:
with open(os.path.join(dirName, '') + "products.json", "w") as write_file:
with open(os.path.join(dirName, '') + 'index.html', 'w') as write_file: