第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法寫入 csv 文件

無法寫入 csv 文件

尚方寶劍之說 2023-09-12 18:28:31
當我嘗試在 csv 文件中寫入信息時,拋出錯誤:Traceback (most recent call last):File "sizeer.py", line 68, in <module>      writer.writerow([name,color,price])                     ValueError: I/O operation on closed fileimport requestsimport csvfrom bs4 import BeautifulSoupproxies = {    "http":"http://195.189.60.97:3128",     "http":"http://103.78.75.165:8080",    "http":"http://212.87.220.2:3128",    "http":"http://88.99.134.61:8080",    "http":"http://103.102.139.178:8080",    "http":"http://218.60.8.83:3129",    "http":"http://124.121.105.193:8888",    "http":"http://198.237.114.54:8080",    "http":"http://36.67.106.58:8080",    "http":"http://35.214.241.28:3128"}base_url = ...page = requests.get(base_url, proxies=proxies)if page.status_code != 200:    exit("Page wasn't parsed")soup = BeautifulSoup(page.content, 'lxml')with open("result.csv", "w") as file:    writer = csv.writer(file)    writer.writerow(["Product","Color","Price"])#Get categoriescategory_wrapper = soup.find_all(class_="m-menu_subItem")categories = []for cw in category_wrapper:    anchor = cw.find("a", recursive=False)    categories.append(anchor['href'])#Iterrate categoriesfor category in categories:    cat_page = requests.get(base_url + category, proxies=proxies)    cat_soup = BeautifulSoup(cat_page.content, 'lxml')    products_wrapper = cat_soup.find(class_="b-productList")    cat_pagination = products_wrapper.find(class_="m-pagination").find_all("span")    max_page = [int(s) for s in cat_pagination[-1].text.split() if s.isdigit()][0]    #Iterrate category with pagination and get products如何在整個腳本執(zhí)行過程中保持文件打開?或者我每次添加內(nèi)容時都必須打開它?編輯事實上,該文件甚至沒有創(chuàng)建。
查看完整描述

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它。


查看完整回答
反對 回復 2023-09-12
  • 1 回答
  • 0 關(guān)注
  • 4060 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號