Home > Mobile >  How to append a new line to a csv file in python
How to append a new line to a csv file in python

Time:05-21

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[@]')
        fraction_price = item.find_elements(By.XPATH, './/span[@]')

        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()

Trying to figure out how to append price to product_price with a new line character at the end.

This has been my outcome and I'm confused why. Do I need to individual print the rows and add a new line. I thought writerow added a new line break already?

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.

CodePudding user response:

writerow without s at the end is for writing all values on list in one row.

And you have all values on one list - so it treats it as single row.

You should rather write row directly when you find price - but price has to be as list.

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

OR you should append price as list with single value

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

            product_price.append( [price] )

and later use writerows with s at the end which write every nested list as separated row

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

BTW: When you write header then you should also use list

csvWriter.writerow( ["Price"] )

beause at this moment it treads "Price" as list of chars

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

and it writes space between chars.


EDIT:

# 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[@]')
        fraction_price = item.find_elements(By.XPATH, './/span[@]')

        if whole_price and fraction_price:

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

PEP 8 -- Style Guide for Python Code

  • Related