提到这个问题,我有一个类似但不一样的问题..
在路上,我会有一些文本文件,结构如下:
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 字典?
PS:我不喜欢使用 .py 文件的解决方案;我更喜欢 .txt、.inc、.whatever 不限于一种语言。