首页 > 解决方案 > 如何读取格式为 [[xxx],[yyy]] 的行的 .txt 文件,以便直接访问 [xxx] 和 [yyy]?

问题描述

我有以这种格式写入文件的脚本,.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])

在这个脚本中,我可以访问 value byprint(List[Row][0][0])或 date bypirnt(List[Row][1][0])

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

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

先感谢您

标签: pythonfor-looptextread-write

解决方案


您可以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


推荐阅读