Ad

How To Read .txt File With Lines Formatted Like [[xxx],[yyy]] In Order Do Access [xxx] And [yyy] Directly?

- 1 answer

I have script that writes .txt file in such format, that is looks like this:

[[1.905568], ['Thu Sep 26 13:17:26 2019']]
[[3.011008], ['Thu Sep 26 13:17:27 2019']]
[[3.10576], ['Thu Sep 26 13:17:28 2019']]
[[2.94784], ['Thu Sep 26 13:17:29 2019']]
              etc.    

Filling .txt file looks like this:

for x in range(len(List)):
        txtfile.write("{}\n".format(List[x])

in this script I can access value by print(List[Row][0][0]) or date by pirnt(List[Row][1][0])

How should i construct for-loop in other script reading this .txt that I could access the data the same way like mentioned above?

Currently I'm reading line by line like: List2 = txtfile.read().split('\n')

Thank you in advance

Ad

Answer

You can use ast for this purpose:

import ast

my_rows = []
with open("path_to_my.txt", "r") as f:
    for line in f:
        row = ast.literal_eval(line)
        my_rows.append(row)

You can now access your values with my_rows[Row][0][0] and dates with my_rows[Row][1][0] with Row corresponding to the row index.

Ad
source: stackoverflow.com
Ad