-1

How can I read a column from a CSV file and turn all of it into a string, and then add it?

import csv

print("HI!, Welcome to spreadsheet reader protype")
fileNameLocator = input("Search file: ") + ".csv"
fileName = open(fileNameLocator)
fileReader = csv.reader(fileName)

# price column
next(fileReader)
for line in fileReader:
    print(line[11])

I have this block of code that prints the desired columns I want from a file, and it gives the numbers vertically as a list, but these numbers are a string, how can I turn them into floats (they are decimals) and then add this numbers(20 or so).

CesarV97
  • 9
  • 4
  • Convert your list of strings to float as per explained https://stackoverflow.com/questions/1614236/in-python-how-do-i-convert-all-of-the-items-in-a-list-to-floats?answertab=active#tab-top – Tayyab Feb 28 '20 at 07:15
  • can you add sample of your file ? – Vikas Periyadath Feb 28 '20 at 07:15
  • Also have a look at pandas, as provide wide range of functionality to manage csv files, https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html – Tayyab Feb 28 '20 at 07:16
  • Does this answer your question? [Defining Data Type during csv file import based on column index in pandas](https://stackoverflow.com/questions/52958349/defining-data-type-during-csv-file-import-based-on-column-index-in-pandas) – Tayyab Feb 28 '20 at 07:20

1 Answers1

0

In Python, to cast something as a float, you pass it into the float constructor.

Example:

number_string = '1.234'
print(type(number_string))
number = float(number_string)
print(type(number))

In your case, it would be something like number = float(line[11]).

kimbo
  • 2,513
  • 1
  • 15
  • 24