关于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 "", line 1, in
#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,。任何对一种语言没有限制的东西。