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

问题描述 投票:0回答:1

我有以这种格式写.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')

提前谢谢您

python for-loop text read-write
1个回答
0
投票

您可以为此目的使用ast

import ast

with open("path_to_my.txt", "r") as f:
    for line in f:
        literal = ast.literal_eval(line)
        row = [e[0] for e in literal]
        print(row)

它将给出此输出:[1.905568, 'Thu Sep 26 13:17:26 2019']

© www.soinside.com 2019 - 2024. All rights reserved.