5

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

Shashikumar KL
  • 715
  • 7
  • 18

5 Answers5

7

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()?

Sayandip Dutta
  • 14,841
  • 3
  • 22
  • 46
1

You can use ast.literal_eval

>>> res = []
>>> with open('f.txt') as f:
...     for line in f:
...             res.append(ast.literal_eval(line))
abc
  • 10,886
  • 2
  • 22
  • 46
0

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.

Masklinn
  • 23,560
  • 2
  • 21
  • 39
0

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]
Maurice Meyer
  • 14,803
  • 3
  • 20
  • 42
-2

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("/")