Search code examples
pythonfor-looptextread-write

How to read .txt file with lines formatted like [[xxx],[yyy]] in order do access [xxx] and [yyy] directly?


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


Solution

  • 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.