Home > database >  convert .cvs list from str to int
convert .cvs list from str to int

Time:02-17

I am training with Python and one of the exercises asks me to extract a column from an csv file and then convert it from str to int

def exercise_column.csv(csv_file_name: str, column_index: int, data_type: str):
  column = []
  with open(file='.cars.csv', mode='r', encodingg='utf8') as file:
    extract_column=file.readline()
    extract_column=file.readline()
    while extract_column:
      extractedcolumn=extract_column.split(sep=',')
      column.append(extractedcolumn[column_index])
      extract_column=file.readline()
  return column

up to this point its all fine, I can extract the columns I need, but then

clients = extract_csv_column(csv_file_name='./cars.csv', column_index=4, data_type='int')
print(clients)

now I'm supposed to get the number of clients for each car, and the result should be in int, but it actually gives the result in str: result

the exercise descrition says I'm supposed to use if/elif/else to convert, but I can't figure out how

CodePudding user response:

Question's been answered, but you may want to change the date_type parameter to type: type. That would allow you to test if the value is of that type, and if not, to convert it:

def exercise_column.csv(csv_file_name: str, column_index: int, data_type: type):
  column = []
  with open(file='.cars.csv', mode='r', encoding='utf8') as file:
    extract_column=file.readline()
    extract_column=file.readline()
    while extract_column:
      extractedcolumn=extract_column.split(sep=',')
      if type(extractedcolumn[column_index]) == data_type:
          column.append(extractedcolumn[column_index])
      else:
          column.append(data_type(extractedcolumn[column_index]))
      extract_column=file.readline()
  return column

CodePudding user response:

You need to cast the values to int as you extract them.

column.append(int(extractedcolumn[column_index]))

As a side note you might consider the variable name row instead of extractedcolumn for readability.

  • Related