0

I have a text file created from a bash script that outputs floats into a list. The contents of the file look like this: [0.2, 0.6, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.1]. I wanted to manipulate this file as a list using Python but Python seems to think its a string and not a list. Below is a sample of my basic Python script:

#!/bin/python3

with open('CPU_Parsed.txt', 'r') as cpu:
        contents = cpu.read()
print(contents)
print(type(contents))
print(list(contents))

When executed the initial print returns: [0.2, 0.6, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.1]. The second print returns 'string'. And when I attempt to turn the entire thing into a list that Python might recognize it parses everything into mush like: ['[', '0', '.', '2', ',', ' ', '0',etc...

My question is how do I get python to read this text file. I want Python to notice the [...] as well as the floats and see it as a list instead of seeing it as a string so that I can further manipulate the list. I appreciate everyone's help!!! Thank you so much!!!!

Mike I
  • 5
  • `import json; lst = json.loads(contents)` – Nick Sep 08 '22 at 03:27
  • @Nick with the fasted draw in all of stackoverflow. You’re awesome. – Mike I Sep 08 '22 at 03:30
  • I've seen this question a few times before :). Glad I could help – Nick Sep 08 '22 at 03:31
  • "The contents of the file look like this: [0.2, 0.6, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.1]. I wanted to manipulate this file as a list using Python but Python seems to think its a string and not a list. " Of course it is a string. You are reading text from a text file. You are trying to *dynamically execute python source code*, for that, you need something like `eval` or `exec`, but you really shouldn't be doing that here in the first place. Use a serialization format, like JSON, to serialize and deserialize your data – juanpa.arrivillaga Sep 08 '22 at 03:36

0 Answers0