用python
例如,我在一个.txt
文件中有变量X、Y和Z,格式如下:
random text
random text
X: 123
Y: 300
random text
X: 22
Y: 34
Z 458.000 random text
random text
我如何将这些值添加到适当的变量中?所以我得到了X = 123 + 22
和Y = 300 + 34
目前我有:
with open('F:/Software/ogamebot/expocounter/allexpo.txt', 'r') as file:
expo_file = file.read()
print(expo_file)
但从这里继续下去的最佳方式是什么
你想做什么还不完全清楚。我的解释是:您有一组预定义的命名变量。如果文件中的一行以变量的名称开头,则需要向该变量添加后续值。具体来说,变量名和给定值之间会有一些空格。以下代码实现此解释:
这当然适用于您的特定示例,但这是您通常想要的吗?例如,变量名和值之间是否总是有空格?还请注意,这段代码不会将值加载到python变量中(即
X
存储为variables['X']
,而不仅仅是X
)-这将更难以整洁的方式完成如果您在文本文件中有一个固定的变量定义模式,比如
VAR: VALUE
,那么下面是我的代码,用于在不基于预定义变量名称的情况下计算它来源数据:
代码如下:
步骤0
从文件中获取数据
步骤1
步骤2
步骤3
最终它是一个三行代码!:)
相关问题 更多 >
编程相关推荐