簡體   English   中英

如何在python中將新行附加到csv文件

[英]How to append a new line to a csv file in python

with open('Price.csv', 'w', newline = '', encoding= 'utf-8') as csvFile:
    csvWriter = csv.writer(csvFile, delimiter=' ')
    csvWriter.writerow("Price")

    for item in items:


        whole_price = item.find_elements(By.XPATH, './/span[@class="a-price-whole"]')
        fraction_price = item.find_elements(By.XPATH, './/span[@class="a-price-fraction"]')

        if whole_price != [] and fraction_price != []:

            price = '.'.join([whole_price[0].text, fraction_price[0].text])
            product_price.append(price)


        else:
            price = 0
   
    csvWriter.writerow(product_price)

driver.quit()

試圖弄清楚如何將 price 附加到 product_price 並在末尾添加一個換行符。

這是我的結果,我很困惑為什么。 我是否需要單獨打印行並添加新行。 我以為 writerow 已經添加了一個新的換行符?

P r i c e
41.18 48.56 18.73 48.56 48.56 37.46 37.46 53.22 60.99 32.99 18.73 7.79 32.34 39.99 20.49 7.79 34.90 37.25 56.49 48.56 156.00 42.95 85.00 34.98 60.00 17.98 60.61 95.50 6.59 7.49 87.40 74.00 17.73 52.56 34.99 39.99 170.00 18.73 2.

最后沒有swriterow用於將列表中的所有值寫入一行。

而且您在一個列表中擁有所有值 - 因此它將其視為單行。

當您找到價格時,您應該直接寫行 - 但price必須作為列表。

            price = '.'.join([whole_price[0].text, fraction_price[0].text])
            
            csvWriter.writerow( [price] )

或者您應該將price附加為具有單個值的列表

            price = '.'.join([whole_price[0].text, fraction_price[0].text])

            product_price.append( [price] )

然后在末尾使用帶有swriterows ,它將每個嵌套列表寫為單獨的行

    csvWriter.writerows(product_price)  # with `s` at the end

順便說一句:當您編寫標題時,您還應該使用列表

csvWriter.writerow( ["Price"] )

因為此時它將"Price"作為字符列表

csvWriter.writerow( ["P", "r", "i", "c", "e"] )

它在字符之間寫入空格。


編輯:

# PEP8: `lower_case_names` for variables `csv_file`, `csv_writer`

with open('Price.csv', 'w', newline='', encoding='utf-8') as csv_file:  
    csv_writer = csv.writer(csv_file, delimiter=' ')
    csv_writer.writerow( ["Price"] )

    for item in items:

        whole_price    = item.find_elements(By.XPATH, './/span[@class="a-price-whole"]')
        fraction_price = item.find_elements(By.XPATH, './/span[@class="a-price-fraction"]')

        if whole_price and fraction_price:

            price = '.'.join([whole_price[0].text, fraction_price[0].text])
            csv_writer.writerow( [price] )

PEP 8——Python 代碼風格指南

暫無
暫無

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

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