0

I have a file called list.txt:

['d1','d2','d3']

I want to loop through all the items in the list. Here is the code:

deviceList = open("list.txt", "r")
deviceList = deviceList.read()
for i in deviceList:
    print(i)

Here the issue is that, when I run the code, it will split all the characters:

% python3 run.py
[
'
d
1
'
,
'
d
2
'
,
'
d
3
'
]

It's like all the items have been considered as 1 string? I think needs to be parsed? Please let me know what am I missing..

user15109593
  • 105
  • 5
  • 7
    You don't have a list yet; you just have a single string which *looks* like a Python list. You have to parse it first with something like `ast.literal_eval`. However, you should consider how `list.txt` was created in the first place, and perhaps replace it with something designed for serializing data structure, like JSON. – chepner May 29 '22 at 20:26
  • 1
    [reference](https://stackoverflow.com/questions/1894269/how-to-convert-string-representation-of-list-to-a-list) for @chepner's answer – sudden_appearance May 29 '22 at 20:28
  • There are no lists in your code. – juanpa.arrivillaga May 29 '22 at 20:29
  • 1
    "It's like all the items have been considered as 1 string?" That's exactly what `read` does. – tobias_k May 29 '22 at 20:33

2 Answers2

0

This isn't the cleanest solution, but it will do if your .txt file is always just in the "[x,y,z]" format.

deviceList = open("list.txt", "r")

deviceList = deviceList[1:-1]
deviceList = deviceList.split(",")

for i in deviceList:
    print(i)

This takes your string, strips the "[" and "]", and then separates the entire string between the commas and turns that into a list. As other users have suggested, there are probably better ways to store this list than a text file as it is, but this solution will do exactly what you are asking. Hope this helps!

0

Simply because you do not have a list, you are reading a pure text...

I suggest writing the list without the [] so you can use the split() function.

Write the file like this: d1;d2;d3

and use this script to obtain a list

f = open("filename", 'r')
line = f.readlines()
f.close()
list = line.split(";")

if you need the [] in the file, simply add a strip() function like this

f = open("filename", 'r')
line = f.readlines()
f.close()
strip = line.strip("[]")
list = strip.split(";")

should work the same