从文本文件中检索变量值的最佳方法? [英] Best way to retrieve variable values from a text file?
问题描述
参考这个问题,我有一个类似的 - 但不是同样的问题..
Referring on this question, I have a similar -but not the same- problem..
在我的路上,我会有一些文本文件,结构如下:
On my way, I'll have some text file, structured like:
var_a: 'home'
var_b: 'car'
var_c: 15.5
我需要 python 读取文件,然后创建一个名为 var_a 的变量,其值为 'home',依此类推.
And I need that python read the file and then create a variable named var_a with value 'home', and so on.
示例:
#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 类型?
Is this possible, I mean, even keep the var type?
请注意,我对文本文件结构拥有完全的自由,如果我建议的格式不是最好的,我可以使用我喜欢的格式.
Notice that I have the full freedom to the text file structure, I can use the format I like if the one I proposed isn't the best.
编辑:ConfigParser 可以是一个解决方案,但我不太喜欢它,因为在我的脚本中,我必须使用
EDIT: the ConfigParser can be a solution, but I don't like it so much, because in my script I'll have then to refer to the variables in the file with
config.get("set", "var_name")
但我喜欢的是直接引用变量,正如我在 python 脚本中声明的那样......
But what I'll love is to refer to the variable directly, as I declared it in the python script...
有没有办法将文件导入为python字典?
There is a way to import the file as a python dictionary?
哦,最后一件事,请记住,我不知道文本文件中到底有多少变量.
Oh, last thing, keep in mind that I don't know exactly how many variables would I have in the text file.
编辑 2:我对 stephan 的 JSON 解决方案非常感兴趣,因为这样可以用其他语言(例如 PHP,然后通过 AJAX JavaScript)简单地读取文本文件,但是我在执行该解决方案时失败了:
Edit 2: I'm very interested at stephan's JSON solution, because in that way the text file could be read simply with others languages (PHP, then via AJAX JavaScript, for example), but I fail in something while acting that solution:
#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 字典?
In what kind of issues can I fall with the JSON format? And, how can I read a JSON array in a text file, and transform it in a python dict?
P.S:我不喜欢使用 .py 文件的解决方案;我更喜欢 .txt、.inc、.whatever 不限于一种语言.
P.S: I don't like the solution using .py files; I'll prefer .txt, .inc, .whatever is not restrictive to one language.
推荐答案
使用 JSON<加载您的文件/a> 或 PyYAML 到字典 the_dict
(参见 JSON 或 PyYAML 文档对于这一步,两者都可以存储数据类型)并将字典添加到您的全局字典中,例如使用 globals().update(the_dict)
.
Load your file with JSON or PyYAML into a dictionary the_dict
(see doc for JSON or PyYAML for this step, both can store data type) and add the dictionary to your globals dictionary, e.g. using globals().update(the_dict)
.
如果你想在本地字典中使用它(例如在函数内部),你可以这样做:
If you want it in a local dictionary instead (e.g. inside a function), you can do it like this:
for (n, v) in the_dict.items():
exec('%s=%s' % (n, repr(v)))
只要使用 exec
是安全的.如果没有,你可以直接使用字典.
as long as it is safe to use exec
. If not, you can use the dictionary directly.
这篇关于从文本文件中检索变量值的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!