Search code examples
pythonsplitnested-loopsnested-listsstrip

Reading data from list with inconsequential whitespacing


I'm a rookie who practicing, how to be better at reading data from files amongst other things.

I'm trying to extract temperature data from a file where the number of spaces between the data elements in the file is inconsequential.

The file in question looks like this:

Year: 1975. Month: November.
10.2   3.2  4.6 12.7 8.9  9.1    10.11
9.4    2.8 10.9  10.7   17.3    2.2    9.6
11.5  6.0 7.4   6.5    10.3 4.5    3.2
4.1  6.7 8.5    6.2    9.9   5.6    3.1
2.3   1.1  14.1

And I would like to append the data into a nested list where every row is a list within a list like this:

[[10.2, 3.2, 4.6, 12.7, 8.9, 9.1, 10.11], [9.4, 2.8, 10.9, 10.7, 17.3, 2.2, 9.6],...,[2.3, 1.1, 14.1]]

Now I know the solution probably involves using nested for-loops, but I'm still in the process of getting more comfortable with them. I have tried a bunch of different types of nested for loops, but none of them seems to give me the result I want.

The closest I've come to a solution is with the following code:

list = []

with open("filename.txt", "r") as file:
    file.readline()
    for line in file:
        line.strip().split("\n")
        list.append(line)

print(list)

which outputs the following:

which clearly is not what I want.

['10.2   3.2  4.6 12.7 8.9  9.1    10.11\n', '9.4    2.8 10.9  10.7   17.3    2.2    9.6\n', (..)', '2.3   1.1  14.1']

If there is someone out there who can help me solve this problem and advance my learning on this topic, I would be very grateful.


Solution

  • As Michael Butscher mentioned, just use split():

    list = []
    
    with open("filename.txt", "r") as file:
        file.readline()
        for line in file:
            row = line.split()
            # convert string list to float list
            row = [float(value) for value in row]
            list.append(row)
    
    print(list)
    

    Output

    [[10.2, 3.2, 4.6, 12.7, 8.9, 9.1, 10.11], [9.4, 2.8, 10.9, 10.7, 17.3, 2.2, 9.6], [11.5, 6.0, 7.4, 6.5, 10.3, 4.5, 3.2], [4.1, 6.7, 8.5, 6.2, 9.9, 5.6, 3.1], [2.3, 1.1, 14.1]]