-4

I have the problem to understand how to import an created and existing array from the file.txt which has just that array in it and save it in the new .py file under an new name to work with it.

the file.txt has following content:

[['name1', 'x', '1', 'a'], ['name2', 'y', '2', 'b'], ['name3', 'b', '3', 'c'], ['name4', '1', '44', '12']]

i tried somethings like that:

text_file = open("file.txt", "r")
lines = text_file.readlines()
print(lines)
text_file.close()  

type is list but i have the same list just with new [""] and same content

print(type(lines))
["[['name1', 'x', '1', 'a'], ['name2', 'y', '2', 'b'], ['name3', 'b', '3', 'c'], ['name4', '1', '44', '12']]"]

and if i try to read the array with

print(lines[1])

or

print(lines[1][2])

i get an error. thx for any help

Update: The answer is:

import ast
  text_file = open("file.txt", "r")
  line          = text_file.readlines();
  lines         = eval(line[0])
  text_file.close()
trash1
  • 3
  • 4
  • You should also look at [saving an object data persistence](https://stackoverflow.com/questions/4529815/saving-an-object-data-persistence). Instead of just writing the list to a text file, use the methods described for better data persistence. – Tomerikoo Nov 05 '20 at 09:45

1 Answers1

-1

Yes, you can use ast.literal_eval:

import ast
text_file = open("file.txt", "r")
lines = ast.literal_eval(text_file.readlines())
print(lines)
text_file.close()  

Here you need to convert the string representation to list.

Wasif
  • 14,755
  • 3
  • 14
  • 34
  • i get the err: AttributeError: 'list' object has no attribute 'strip' – trash1 Nov 05 '20 at 09:41
  • tried but i get somefails like that: Traceback (most recent call last): File "etzu786438zhrezbg_v7.py", line 161, in lines = ast.literal_eval(text_file.readlines()) File "/usr/lib/python3.7/ast.py", line 91, in literal_eval return _convert(node_or_string) File "/usr/lib/python3.7/ast.py", line 90, in _convert return _convert_signed_num(node) File "/usr/lib/python3.7/ast.py", line 63, in _convert_signed_num return _convert_num(node) – trash1 Nov 05 '20 at 10:59
  • and that: File "/usr/lib/python3.7/ast.py", line 55, in _convert_num raise ValueError('malformed node or string: ' + repr(node)) ValueError: malformed node or string: ["[['rs4477212', '1', '82 ... – trash1 Nov 05 '20 at 10:59