ethanruan ethanruan - 7 months ago 13
Python Question

Import CSV to list of list Python

Python newbie here.

I have a CSV file containing numbers in this kind of format

9143.680696, 427953.500000, 11919.104475, 11908.727555, 1.000871, 0.029506, 15.546608, 93, 121, 123, 7
7704.773182, 330297.500000, 19186.759308, 19170.146116, 1.000867, 0.029426, 14.302257, 93, 121, 123, 7


I need to read the file such that the list will go like this

[
[[9143.680696, 427953.500000, 11919.104475, 11908.727555, 1.000871, 0.029506, 15.546608, 93, 121, 123], [7]],
[[7704.773182, 330297.500000, 19186.759308, 19170.146116, 1.000867, 0.029426, 14.302257, 93, 121, 123], [7]]
]


The last number of every line is stored in a different list like in the case of 7 here.

I have researched some of the answers here but have found that they are stored as strings into the list which would not be compatible to the problem I am dealing with.

Thank you in advance for your help.



Answer

The simplest approach without using external modules:

Update: I replaced the simple float(...) conversions with the new convert(...) method that tries to produce a float and returns the original string (or alternatively could do something else) instead of throwing an exception if the token is not a number.

def convert(value_str):
    try:  # try to convert it to a float:
        return float(value_str)
    except ValueError:  # if it is not a valid float literal, return the original string:
        return value_str

with open("file.csv") as csvfile:
    split_lines = [line.split(",") for line in csvfile]
    data = [[[convert(n) for n in line[:-1]], [convert(line[-1])]] for line in split_lines]

    print(data)

Output for your example data from the question (formatted manually):

[
  [ [9143.680696, 427953.5, 11919.104475, 11908.727555, 1.000871, 0.029506, 15.546608, 93.0, 121.0, 123.0], [7.0] ],
  [ [7704.773182, 330297.5, 19186.759308, 19170.146116, 1.000867, 0.029426, 14.302257, 93.0, 121.0, 123.0], [7.0] ]
]
Comments