如何读取格式为 [[xxx],[yyy]] 的 .txt 文件以便直接访问 [xxx] 和 [yyy]?
How to read .txt file with lines formatted like [[xxx],[yyy]] in order do access [xxx] and [yyy] directly?
我有脚本以这种格式写入 .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')
提前致谢
您可以使用 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
对应于行索引。
我有脚本以这种格式写入 .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')
提前致谢
您可以使用 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
对应于行索引。