Reading a text file accurately in Python

Question:

I am trying to read a .txt file. However, the output is in strings and I don’t get the actual array. I present the current and expected outputs below.

import numpy as np
with open('Test.txt') as f:
    A = f.readlines()
    print(A)

The current output is

['[array([[1.7],n', '       [2.8],n', '       [3.9],n', '       [5.2]])]']

The expected output is

[array([[1.7],
       [2.8],
       [3.9],
       [5.2]])]
Asked By: user19862793

||

Answers:

By using regex and ast.literal_eval :

import re
import ast

#Your output
s = ['[array([[1.7],n', '       [2.8],n', '       [3.9],n', '       [5.2]])]']

#Join them
s = ' '.join(s)

#Find the list in string by regex
s  = re.findall("(([[wW]*]))",s)

#Convert string to list
ast.literal_eval(s[0])

Output:

[[1.7], [2.8], [3.9], [5.2]]

By using regex and eval :

import re

#Your output
s = ['[array([[1.7],n', '       [2.8],n', '       [3.9],n', '       [5.2]])]']

#Join them
s = ' '.join(s)

#Find the list in string by regex
s  = re.findall("(([[wW]*]))",s)

#Convert string to list
eval(s[0])

Output:

[[1.7], [2.8], [3.9], [5.2]]
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.