Python 如何读取格式为[[xxx]、[yyy]]的行的.txt文件,以便直接访问[xxx]和[yyy]?
我有一个脚本,它以这样的格式编写Python 如何读取格式为[[xxx]、[yyy]]的行的.txt文件,以便直接访问[xxx]和[yyy]?,python,for-loop,text,read-write,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. for x in range(len(List)):
.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.
for x in range(len(List)):
txtfile.write("{}\n".format(List[x])
填充.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.
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')
提前感谢您您可以使用
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]
访问与行索引对应的日期