Home > OS >  Reading a text file accurately in Python
Reading a text file accurately in Python

Time:09-10

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]])]

CodePudding user response:

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("\((\[[\w\W]*\])\)",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("\((\[[\w\W]*\])\)",s)

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

Output:

[[1.7], [2.8], [3.9], [5.2]]
  • Related