1 回答
TA贡献1784条经验 获得超8个赞
with open("result.csv", "w") as file:
writer = csv.writer(file)
writer.writerow(["Product","Color","Price"])
文件在with块的末尾关闭——这就是块的目的。
您可以将所有内容都放在块内,但这只会使现有问题变得更糟:代码达到了多层缩进,很长并且变得难以理解。这就是为什么使用函数来组织代码的原因。例如,如果您for在函数中设置了大循环:
def do_stuff_with(categories, writer):
for category in categories:
# lots of logic here
# use `writer.writerow` when needed
# Get everything else set up that doesn't need the file, first
categories = ... # do the BeautifulSoup input stuff
# then we can open the file and use the function:
with open("result.csv", "w") as file:
writer = csv.writer(file)
writer.writerow(["Product","Color","Price"])
do_stuff_with(categories, writer)
一旦你完成了这项工作,你可能就能想出进一步应用该技术的方法。例如,拉出最里面的逻辑,用于处理variations单个产品。或者你可以有一个函数来处理数据的创建categories,然后return它。
添加回答
举报