python - 我想从 txt 文件中提取 x 和 y 值
问题描述
我有一些代码将 x 和 y 值存储到 txt 文件中。每次我告诉程序存储数据时,txt 文件都会在每一行存储值。
它在 txt 文件中是这样写的:
[(1.0, 1.80), (2.0, 1.80), (3.0, 0.70), etc...]
我尝试使用该np.genfromtxt()
函数提取值,但我一直在获取这些值nan
。我通读了文档,但似乎无法解释它。
如何将这些 x 和 y 值存储到变量中,以便在 txt 文件之外进一步使用它们?
解决方案
使用ast
模块
前任:
import ast
with open(filename) as infile: #Read file
for line in infile: #Iterate Each line
print(ast.literal_eval(line)) #Convert to python object
输出:
[(1.0, 1.8), (2.0, 1.8), (3.0, 0.7)]
[(1.0, 1.8), (2.0, 1.8), (3.0, 0.7)]
[(1.0, 1.8), (2.0, 1.8), (3.0, 0.7)]
推荐阅读
- php - 我可以使用 macOS High Sierra 更新到最新版本的 PHP
- python - 如何使用 PANDAS 过滤掉一行?
- excel - Excel中的Sumifs与日期计算
- quire-api - 如何在 Quire 应用中接受用户配置?
- c# - 网络框架上的包引用不加载传递依赖项(未在输出中复制)
- swift - 如果按下按钮,则仅在 for 循环内继续
- reactjs - 在反应中通过主题提供者的材料 UI 多种字体
- python - 将列名中的字符串转换为 Pandas 中的 DateTime 对象
- date - 火花年龄计算间隔数据类型
- python-3.x - 通过文件夹中的上下文菜单打开 Powershell 时出现错误消息