How to call an input file (saved as a list in list) seprated by commas?

Question:

I have a saved file in the form of lists,
[-17.43351952][-3.3481323][-17.43351952][-0.10026689][-0.10026689]
now i want to open the file and use it’s values for doing some Arithmetic operations.

when i call it , it comes as one single unit (as a string ” ), without separation of any commas.

i tried but it didn’t worked.

with open('text_file.txt') as f:
    data = f.read().replace(" ", ",")

print(data)

i also tried using split function, but 'list' object has no attribute 'split'

desired output

`
[-17.43351952], [-3.3481323], [-17.43351952], [-0.10026689], [-0.10026689]

`

Asked By: walter white

||

Answers:

You should put more thought into how you’re saving your data to ensure you can easily recover it. Regardless, you can split at ][, and remove the first [ and final ] by slicing with [1:-1]:

[[float(x)] for x in f.read()[1:-1].split('][')]
# [[-17.43351952], [-3.3481323], [-17.43351952], [-0.10026689], [-0.10026689]]

Note that this is fragile: if there is a space between two of the lists, then this approach won’t work. You can solve this more generally using regular expressions, but it is always preferable to not end up in this situation at all and to use something like pickle or json or pandas to save your data in a more easily readable format.

It’s also unclear why the lists are nested, so you could also just use:

[float(x) for x in f.read()[1:-1].split('][')]
# [-17.43351952, -3.3481323, -17.43351952, -0.10026689, -0.10026689]
Answered By: Kraigolas
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.