D R
D R

Reputation: 21

python Quick way to read formatted data from txt file

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

Answers (3)

Demi-Lune
Demi-Lune

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

Carson
Carson

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

balderman
balderman

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

Related Questions