Reading multiple arrays in a text file in Python

Question:

I am trying to read multiple arrays saved in .txt file. I present the data in Test.txt file as well as the current and expected outputs.

import re
import numpy as np
import ast

with open('Test.txt') as f:
    s = f.readlines()
    #print(s)
    s = ' '.join(s)
    s  = re.findall("(([[wW]*]))",s)
    s=ast.literal_eval(s[0])
    s=np.array(s)
    print([s])

The data in Test.txt is

[array([[1.7],
       [2.8],
       [3.9],
       [5.2]])]
[array([[2.1],
       [8.7],
       [6.9],
       [4.9]])]

The current output is

line 4
    [5.2]])]
          ^
SyntaxError: unmatched ')'

The expected output is

[array([[1.7],
       [2.8],
       [3.9],
       [5.2]])]
[array([[2.1],
       [8.7],
       [6.9],
       [4.9]])]
Asked By: user19862793

||

Answers:

You can use this:

import re
import ast

s = '''
    [array([[1.7],[2.8],[3.9],
       [5.2]])]
[array([[2.1],
       [8.7],
       [6.9],
       [4.9]])]
'''

s = s.replace('n', '')
s = s.replace(' ', '')
s = s[1:-1]
s = re.findall("(([.*?]))",s)

result= []

for i in s:
    result.append(ast.literal_eval(i))
    
print(result)

Output:

[[[1.7], [2.8], [3.9], [5.2]], [[2.1], [8.7], [6.9], [4.9]]]
Answered By: Shahab Rahnama
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.