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
  • 1,007
  • 1
  • 10
  • 25

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
  • 15,602
  • 4
  • 23
  • 52
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
  • 11,579
  • 2
  • 26
  • 51
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
  • 34,759
  • 3
  • 38
  • 57
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
  • 17,279
  • 4
  • 30
  • 47
-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("/")