1

I have a file with “mark,19,2050.50,Chris,20,2010.40” as its content. If I read the file using open(), the contents are assigned into the file as textIOwrapper. If I split and store it in a list using the delimiter(‘,’ in this case) the list contains the values as strings.

For eg : [‘mark’,’19’,’2050.50’, ‘Chris’,’20’,’2010.40’]

I need the output to be

[‘mark’, 19, 2050.50, ‘Chris’,20,2010.40]

Any idea how to do this? Thanks

Akhila
  • 3,235
  • 1
  • 14
  • 30
Rahul
  • 161
  • 2
  • 6

3 Answers3

0

You can't read the specific data types, because you don't know the data types. Everything in a file is assumed to be a string.

You could try to check for some specific cases, but you are better off using a library that already does that for you. Use panda's function pandas.read_csv.

blue_note
  • 27,712
  • 9
  • 72
  • 90
0

Here is a SO solution for an autocast. He uses it as a decorator, but basically the function alone would also accomplish what you need. It just tries to cast it as either int, float or if both fail, as a string. Nevertheless, if you parse big files that might slow it down. If you have more than the base types it probably won't be as easy.

JennyH
  • 292
  • 1
  • 2
  • 11
0

eval() seems to do the trick for basic data types

Thanks for the suggestions

Rahul
  • 161
  • 2
  • 6