如何读取格式为[[xxx],[yyy]]的行的.txt文件,以便直接访问[xxx]和[yyy]?

时间:2019-09-27 07:32:09

标签: python for-loop text read-write

我有一个脚本以这种格式写入.txt文件,看起来像这样:

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

填充.txt文件如下:

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

在此脚本中,我可以按print(List[Row][0][0])访问值,也可以按pirnt(List[Row][1][0])访问日期

我应该如何在其他读取此.txt的脚本中构造for循环,以便我可以像上面提到的一样访问数据?

目前我正在逐行阅读,例如:List2 = txtfile.read().split('\n')

提前谢谢

1 个答案:

答案 0 :(得分:1)

您可以将ast用于此目的:

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)

您现在可以使用my_rows[Row][0][0]访问值,并使用my_rows[Row][1][0]Row访问日期,这些行与行索引相对应。