Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]

`

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading