Changing strings to floats in an imported .csv

前端 未结 4 1140
梦毁少年i
梦毁少年i 2020-12-16 13:23

Quick question for an issue I haven\'t managed to solve quickly:

I\'m working with a .csv file and can\'t seem to find a simple way to convert strings to floats. Her

4条回答
  •  我在风中等你
    2020-12-16 14:10

    Try something like the following

    import csv
    
    def read_lines():
        with open('testdata.csv', 'rU') as data:
            reader = csv.reader(data)
            for row in reader:
                yield [ float(i) for i in row ]
    
    for i in read_lines():
        print(i)
    
    # to get a list, instead of a generator, use
    xy = list(read_lines())
    

    As for the easiest way, then I suggest you see the xlrd, xlwt modules, personally I always have hard time with all the varying CSV formats.

提交回复
热议问题