Reputation: 21
I am trying to find a best way to read array from text file, which is in format:
"filename.txt"
points = [
[2.0, 0.0],
[3.0, 2.0],
[2.5, 2.0],
[0.0, 1.5],
[0.0, 0.0]
]
I know how to use readline
to separate the data line by line, but are there simpler ways?
Upvotes: 1
Views: 1671
Reputation: 1967
If it is really python syntax, rename it to data.py and import it (or use importlib). Using directly python syntax for datafile is one of the powerful features of python.
Upvotes: 1
Reputation: 7968
import ast
with open('filename.txt', 'r') as f:
data = f.read()
data = data[data.find('=') + 1:]
for remove_chr in ('\n', '\t', ' '):
data = data.replace(remove_chr, '')
points = ast.literal_eval(data)
print(type(points).__name__, points)
output:
list [[2.0, 0.0], [3.0, 2.0], [2.5, 2.0], [0.0, 1.5], [0.0, 0.0]]
Upvotes: 0
Reputation: 23815
If you will remove the 'points = ' from the file you will get a data structure that can be loaded using json.load()
import json
with open("my_file_after_cleanup.json", "r") as read_file:
data = json.load(read_file)
Upvotes: 2