Search code examples
stringpython-2.7texttype-conversionfloating-point-conversion

Python: How can read as float numbers a series of strings from a text file?


I'm trying to read from a text file line by line a series of strings like these:

11,52.15384615384615,52.84615384615385,14.0,45.15384615384615,39.76923076923077
10,27.09090909090909,54.81818181818182,64.36363636363636,65.54545454545455,21.90909090909091

(The first number is an integer used as index), and what I would like to get are float numbers such as

11, 52.15, 52.85, 14.00, 45.15, 39.77
10, 27.09, 54.82, 64.36, 65,54, 21.91

How can I convert these strings to a list of numbers?


Solution

  • Sounds like you are trying to get a list of floats together from a text file. You can use a dict to map the index you mention to the list of floats. Then just open the file, read line by line, use split(',') to split the string into a list of strings. Then grab the first integer as you index, use list slice to look the rest of the strings and convert/round them and add them to a new list which you can later assign to your index.

    It's easier to read the code probably than it is to explain it.

    my_float_dict = dict()
    with open('my_float_strings.txt','r') as f:
        for line in f:
    
            string_list = line.split(',')
    
            index = int(string_list[0])
    
            line_float_list = []
            for field in string_list[1:]:
                line_float_list.append(round(float(field),2))
    
            my_float_dict[index] = line_float_list
    
    print my_float_dict