0

I have export.csv file, with data

name,total
candy,10
ice cream,15
potatoe chips,20 

when i read the .csv file with this code

with open('files/export.csv','r') as file_csv:
    read= list(csv.reader(file_csv))
    for row in read:
        print(row)

Turns out that the data in the total column is a string data type not a float. I want the output be like this:

"name","total"
"candy",10
"ice cream",15
"potatoe chips",20

So I can sum and take the total column data.

1
  • 1
    The float builtin can convert a string to a float as long as it is in Python's literal float format. Commented Dec 11, 2020 at 7:13

2 Answers 2

2

To convert the 2nd field into floats, the following should work for you:

import csv

with open('files/export.csv','r') as file_csv:
    read = list(csv.reader(file_csv))
    for i, row in enumerate(read):
        if i > 0:
            row[1] = float(row[1])
        print(row)

Though do note, that here, we have to skip the first row (header) to apply the conversion only to the data itself.

Sign up to request clarification or add additional context in comments.

Comments

1

Try to read it with pandas. Give really strong support to csv files.

Code

import pandas
pandas.read_csv('files/export.csv')

Results

Results

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.