python - 从文本文件中检索变量值的最佳方法?

引用 this question ,我有一个类似但不一样的问题..

在路上,我会有一些文本文件,结构如下:

var_a: 'home'
var_b: 'car'
var_c: 15.5

我需要 python 读取文件,然后创建一个名为 var_a 的变量,其值为 'home',依此类推。

例子:

#python stuff over here
getVarFromFile(filename) #this is the function that im looking for
print var_b
#output: car, as string
print var_c
#output 15.5, as number.

这可能吗,我的意思是,甚至保留 var 类型?

请注意,我对文本文件结构拥有完全的自由,如果我提出的格式不是最好的,我可以使用我喜欢的格式。

编辑:ConfigParser 可以是一个解决方案,但我不太喜欢它,因为在我的脚本中我将不得不引用文件中的变量

config.get("set", "var_name")

但我喜欢直接引用变量,就像我在 python 脚本中声明的那样......

有没有办法将文件导入为 python 字典?

哦,最后一件事,请记住,我不知道文本文件中有多少变量。

编辑 2:我对 stephan 的 JSON 解决方案非常感兴趣,因为这样可以使用其他语言(例如 PHP,然后通过 AJAX JavaScript)简单地读取文本文件,但是我在执行该解决方案时失败了:

#for the example, i dont load the file but create a var with the supposed file content
file_content = "'var_a': 4, 'var_b': 'a string'"
mydict = dict(file_content)
#Error: ValueError: dictionary update sequence element #0 has length 1; 2 is required
file_content_2 = "{'var_a': 4, 'var_b': 'a string'}"
mydict_2 = dict(json.dump(file_content_2, True))
#Error:
#Traceback (most recent call last):
#File "<pyshell#5>", line 1, in <module>
#mydict_2 = dict(json.dump(file_content_2, True))
#File "C:\Python26\lib\json\__init__.py", line 181, in dump
#fp.write(chunk)
#AttributeError: 'bool' object has no attribute 'write'

JSON 格式可以解决哪些问题? 还有,如何读取文本文件中的 JSON 数组,并将其转换为 python dict?

P.S:我不喜欢使用 .py 文件的解决方案;我更喜欢 .txt、.inc、.whatever 不限于一种语言。

最佳答案

But what i'll love is to refer to the variable direclty, as i declared it in the python script..

假设您愿意稍微更改语法,只需使用 python 并导入“config”模块。

# myconfig.py:

var_a = 'home'
var_b = 'car'
var_c = 15.5

那就做吧

from myconfig import *

您可以在当前上下文中按名称引用它们。

https://stackoverflow.com/questions/924700/

相关文章:

json - 如何将 JSON 文件导入 TypeScript 文件?

json - 如何将 Django 查询集输出为 JSON?

ruby-on-rails-3 - 如何使用 ActiveModel::Serializers 为同

javascript - 使用 jQuery 检查 JSON 对象中是否存在键

javascript - 有没有一种快速的方法可以在文本编辑器中将 JavaScript 对象转换为

javascript - Ajax调用完成后执行函数

json - Newtonsoft 对象 → 获取 JSON 字符串

java - 如何将 JSON 字段名称映射到不同的对象字段名称?

django - 使用 django 测试客户端发送 JSON

java - Gson 将一组数据对象转换为 json - Android