简体   繁体   中英

CSV - How to read and write row by row?

I have a CSV file like this:

csv文件截图

In Python 3 I am already parsing price data from URL like this:

source1 = "https://www.amazon.com/product1"
source2 = "https://www.ebay.com/product1"
source3 = "https://www.bestbuy.com/product1"

Getting Price data like this:

result1 = trim.sub('', mystring1)
result2 = trim.sub('', mystring2)
result3 = trim.sub('', mystring3)

Now I want to read the above the top CSV file want to feed each row's URL into:

source1 = "read.csv"
source2 = "read.csv"
source3 = "read.csv"

and update the price column using result1 , result2 , and result3 , then go to the next row do the same again.

Can anyone help me how to read and write CSV file like this?

I was able to read the CSV list one by one but when I am trying to write to a new file it is writing like the following picture

在此处输入图片说明

Here is the code. It is creating a new row

import csv


with open('compare_sheet', 'w', newline='') as csv_file:
    fieldnames = ['ProductName', 'Amazon', 'Ebay', 'BestBuy']
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writeheader()

    product = pr_name.text
    result1 = trim.sub('', mystring1)
    print(result1)
    writer.writerow({'ProductName': product, 'Amazon': result1})

    result2 = trim.sub('', mystring2)
    print(result2)
    writer.writerow({'Ebay': result2})

    result3 = trim.sub('', mystring3)
    print(result3)
    writer.writerow({'BestBuy': result3})

How can I write price on same line?

Like its name says, writerow writes a complete row. You want to assemble all the results into one row, like this;

writer.writerow({'ProductName': product, 'Amazon': result1, 'Ebay': result2, 'BestBuy': result3})

Obviously you can only do this when you have populated all three variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM