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

Str*_*rae 38 python variables text-files

参考这个问题,我有一个类似但不一样的问题..

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

var_a: 'home'
var_b: 'car'
var_c: 15.5
Run Code Online (Sandbox Code Playgroud)

我需要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.
Run Code Online (Sandbox Code Playgroud)

这是否可能,我的意思是,即使保留var类型?

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

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

config.get("set", "var_name")
Run Code Online (Sandbox Code Playgroud)

但我喜欢的是直接引用变量,就像我在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'
Run Code Online (Sandbox Code Playgroud)

我可以在JSON格式中遇到什么样的问题?而且,我如何在文本文件中读取JSON数组,并在python dict中转换它?

PS:我不喜欢使用.py文件的解决方案; 我更喜欢.txt,.inc,.对一种语言没有限制.

hbn*_*hbn 67

但我喜欢的是引用变量direclty,正如我在python脚本中声明的那样.

假设您很乐意稍微改变语法,只需使用python并导入"config"模块即可.

# myconfig.py:

var_a = 'home'
var_b = 'car'
var_c = 15.5
Run Code Online (Sandbox Code Playgroud)

然后做

from myconfig import *
Run Code Online (Sandbox Code Playgroud)

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

  • +1,这绝对是配置文件的最佳方式.当你可以重新使用python的核心部分时,无需增加自己的配置语法,配置解析器,配置加载器等! (4认同)
  • +1是的,只要您可以信任您的配置文件并且不需要可移植性 (3认同)
  • 方便性和灵活性++与安全性 - 在某些情况下它很好,在其他情况下......不那么好. (2认同)
  • 我必须放弃这个解决方案,因为我不想只将文件限制为 python,我认为最好使用其他语言也可以访问的通用文件格式(.txt、.inc、.whatever)(包括所有此解决方案将意味着的安全措施)。无论如何,我会记住这样的未来 (2认同)
  • 如果您更改软件中的选项并希望将更改保存到磁盘,您也会失去写入支持 (2认同)

Nic*_*kis 24

您可以文本文件视为python模块并使用imp.load_source以下命令动态加载它:

import imp
imp.load_source( name, pathname[, file]) 
Run Code Online (Sandbox Code Playgroud)

例:

// mydata.txt
var1 = 'hi'
var2 = 'how are you?'
var3 = { 1:'elem1', 2:'elem2' }
//...

// In your script file
def getVarFromFile(filename):
    import imp
    f = open(filename)
    global data
    data = imp.load_source('data', '', f)
    f.close()

# path to "config" file
getVarFromFile('c:/mydata.txt')
print data.var1
print data.var2
print data.var3
...
Run Code Online (Sandbox Code Playgroud)

  • `importlib` 会变成什么?imp 正在被弃用 (2认同)

Igo*_*kon 24

使用ConfigParser.

你的配置:

[myvars]
var_a: 'home'
var_b: 'car'
var_c: 15.5
Run Code Online (Sandbox Code Playgroud)

你的python代码:

import ConfigParser

config = ConfigParser.ConfigParser()
config.read("config.ini")
var_a = config.get("myvars", "var_a")
var_b = config.get("myvars", "var_b")
var_c = config.get("myvars", "var_c")
Run Code Online (Sandbox Code Playgroud)


ste*_*han 15

使用JSONPyYAML将文件加载到字典中the_dict(请参阅此步骤的JSON或PyYAML文档,两者都可以存储数据类型)并将字典添加到您的全局字典中,例如使用globals().update(the_dict).

如果你想要它在本地字典中(例如在函数内),你可以这样做:

for (n, v) in the_dict.items():
    exec('%s=%s' % (n, repr(v)))
Run Code Online (Sandbox Code Playgroud)

只要它是安全的使用exec.如果没有,您可以直接使用字典.

  • 较短的习语是globals().update(the_dict)或locals().update(the_dict). (2认同)

Jor*_*rza 5

假设您有一个名为“test.txt”的文件,其中包含:

a=1.251
b=2.65415
c=3.54
d=549.5645
e=4684.65489
Run Code Online (Sandbox Code Playgroud)

你想找到一个变量(a、b、c、d 或 e):

ffile=open('test.txt','r').read()

variable=raw_input('Wich is the variable you are looking for?\n')

ini=ffile.find(variable)+(len(variable)+1)
rest=ffile[ini:]
search_enter=rest.find('\n')
number=float(rest[:search_enter])

print "value:",number
Run Code Online (Sandbox Code Playgroud)


小智 5

这里发布的其他解决方案对我不起作用,因为:

  • 我只需要一个普通脚本的文件参数
  • import * 对我不起作用,因为我需要一种方法来通过选择另一个文件来覆盖它们
  • 只是一个带有字典的文件并不好,因为我需要评论.

所以我最终使用Configparserglobals().update()

测试文件:

#File parametertest.cfg:
[Settings]
#Comments are no Problem
test= True
bla= False    #Here neither

#that neither
Run Code Online (Sandbox Code Playgroud)

这是我的演示脚本:

import ConfigParser

cfg = ConfigParser.RawConfigParser()
cfg.read('parametertest.cfg')       # Read file

#print cfg.getboolean('Settings','bla') # Manual Way to acess them

par=dict(cfg.items("Settings"))
for p in par:
    par[p]=par[p].split("#",1)[0].strip() # To get rid of inline comments

globals().update(par)  #Make them availible globally

print bla
Run Code Online (Sandbox Code Playgroud)

它只适用于现在有一个部分的文件,但这很容易采用.

希望它会对某人有所帮助:)