簡體   English   中英

如何f.write .append結果為CSV

[英]How to f.write .append results to CSV

我編輯了一些Python代碼來使用.append方法,這意味着我編寫f.write()將不再起作用( TypeError: can only concatenate list (not "str") to list )。

這是刮刀的一部分,我已經測試並可以打印。 在編輯我的循環以包含.append之前,我使用以下代碼行導出到.csv:

f.write(product_name + "," + product_number + "," + category + "\n")

這將不再有效,我不知道如何編輯它。 任何幫助將不勝感激。

我編輯了我的循環看起來像這樣:

containers = page_soup.findAll("tr",{"class":"products"})

product_name = []
product_number = []
category = []

for container in containers:
    product_name.append( container.a.text )
    product_number.append( container.div.text )
    category.append( container.select_one('td:nth-of-type(4)').text.strip() )

我相信我明白添加.append方法意味着我不能使用上面顯示的f.write方法(列表與字符串,對吧?)。 當我使用上面顯示的f.write代碼時,我得到一個“ TypeError: can only concatenate list (not "str") to list ”,我認為我理解。

我知道我的循環正在運行,因為這段代碼會產生正確的結果:

print("product_name:", product_name)
print("product_number:", product_number)
print("category: ", category)

我現在如何寫這個.csv?

為避免迭代兩次項目,您只需在for循環中寫入文件:

product_names = []
product_numbers = []
categories = []

with open('file.csv','w') as f:
    for container in containers:
            product_name = container.a.text
            product_number = container.div.text
            category =  container.select_one('td:nth-of-type(4)').text.strip() 

            product_names.append(product_name)
            product_numbers.append(product_number)
            categories.append(category)

            f.write(product_name + "," + product_number + "," + category + "\n")

您可能還希望使用csv模塊將行寫入文件,而不是手動使用字符串連接來創建行:

import csv

with open('file.csv','w') as f:
    csv_out = csv.writer(f)
    for container in containers:
            #...same as above...

            csv_out.writerow([product_name, product_number, category])

與以前一樣,只需在建立product_nameproduct_numbercategory的完整內容后執行此操作,並一次執行一行:

items = zip(product_name, product_number, category)  # zip these three lists into a single 2D list
with open("my_file.csv", 'w') as f:
    for item in items:
        f.write(f"{item[0]},{item[1]},{item[2]}\n")

如果你遇到比這更復雜的事情,你也可以考慮使用csv庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM