1 回答

TA貢獻1784條經(jīng)驗 獲得超8個贊
with open("result.csv", "w") as file:
writer = csv.writer(file)
writer.writerow(["Product","Color","Price"])
文件在with塊的末尾關(guān)閉——這就是塊的目的。
您可以將所有內(nèi)容都放在塊內(nèi),但這只會使現(xiàn)有問題變得更糟:代碼達到了多層縮進,很長并且變得難以理解。這就是為什么使用函數(shù)來組織代碼的原因。例如,如果您for在函數(shù)中設(shè)置了大循環(huán):
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)
一旦你完成了這項工作,你可能就能想出進一步應用該技術(shù)的方法。例如,拉出最里面的邏輯,用于處理variations單個產(chǎn)品?;蛘吣憧梢杂幸粋€函數(shù)來處理數(shù)據(jù)的創(chuàng)建categories,然后return它。
添加回答
舉報