Shashikumar KL
Shashikumar KL

Reputation: 1085

How to converting string to list?

I have a file and its consist of multiple lists like below

[234,343,234]
[23,45,34,5]
[354,45]
[]
[334,23]

I am trying to read line by line and append to a single list in python.

how to do it?

I tried so far>

with open("pos.txt","r") as filePos:
    pos_lists=filePos.read()
new_list=[]
for i in pos_lists.split("\n"):
    print(type(i)) #it is str i want it as list
    new_list.extend(i)

print(new_list)

thanks in advance

Upvotes: 5

Views: 157

Answers (5)

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

You can try these:

>>> from ast import literal_eval
>>> with open(YOURTEXTFILE) as f:
...    final_list = [literal_eval(elem) for elem in f.readlines()]
>>> final_list
[[234, 343, 234], [23, 45, 34, 5], [354, 45], [], [334, 23]]

Or,

>>> from ast import literal_eval
>>> with open(YOURTEXTFILE) as f:
...    final_list = sum(map(literal_eval, s.readlines()), [])
>>> final_list
[234, 343, 234, 23, 45, 34, 5, 354, 45, 334, 23]

Whichever you want.

The same thing can be done with python built-in eval() however, it is not recommended to use eval() on untrusted code, instead use ast.literal_eval() which only works on very limited data types. For more on this, see Using python's eval() vs. ast.literal_eval()?

Upvotes: 7

Maurice Meyer
Maurice Meyer

Reputation: 18126

In case each line is a valid JSON array/object, you can use jsonlines:

import jsonlines
r = []
with jsonlines.open('input.jsonl') as reader:
    for line in reader:
        for item in line:
            r.append(item)
print(r)

Output:

[234, 343, 234, 23, 45, 34, 5, 354, 45, 334, 23]

Upvotes: 0

wannes jacobus
wannes jacobus

Reputation: 45

you can use the split() method between the brackets you can give a symbol to split by.

between the brackets give the symbol you want to split it by. Maybe like this:

txt = "[234,343,234]/[23,45,34,5]/[354,45]/[]/[334,23]"        
x = txt.split("/")

Upvotes: -2

abc
abc

Reputation: 11929

You can use ast.literal_eval

>>> res = []
>>> with open('f.txt') as f:
...     for line in f:
...             res.append(ast.literal_eval(line))

Upvotes: 1

Masklinn
Masklinn

Reputation: 42472

If the lines are assumed and intended to be python literals you can just ast.literal_eval(line).

For safety you may want to assume they are JSON values instead, in which case json.loads(line) should do the trick.

Upvotes: 0

Related Questions