python - 如何读取格式为 [[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')
先感谢您
解决方案
您可以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
推荐阅读
- html - 背景img模糊 - css
- r - 如何将geom_bar的宽度调整为相同的宽度
- c - 如何在 C 中的线程执行后请求用户输入
- php - opencart和mysql db之间的连接
- python - Python 索引错误 parse_results = result.get("Parsed Results")[0]
- css - CSS相同的属性声明不起作用
- asp.net - 浏览器中的视图选项如何在没有 IIS 的 Visual Studio 中工作?
- php - Laravel 使用 BelongsToMany 中关联的类别过滤用户
- lua - 如何在获得地址的同时获得表格的行
- javascript - 类型“未知”不可分配给类型“从不”.ts(2322)