简体   繁体   English

从文本文件中读取列表

[英]Read list from text file

I have been experimenting with ways of storing some variables from my python project in a user readable/editable text file. 我一直在尝试将python项目中的一些变量存储在用户可读/可编辑的文本文件中的方法。 The text file is laid out like this: 文本文件的布局如下:

a = "hello"
b = 123
c = [4,5,6]

As you can see, a is meant to be a string, b an integer, and ca list. 如您所见,a表示字符串,b表示整数,以及ca列表。 The code I have so far goes as follows: 到目前为止,我的代码如下:

for line in file:
    name = line.split('=')[0]
    value = line.split('=')[1]
    vars()[name] = value

It splits the line at the '=' and sets the first section as the variable name, and the second section as the value for that variable. 它在'='处分割行,并将第一部分设置为变量名称,第二部分设置为该变量的值。

However, when the program runs, instead of coming out as an integer and a list, b (123) and c ([4,5,6]) both are saved as strings. 但是,当程序运行时,b(123)和c([4,5,6])不会作为整数和列表出现,而是另存为字符串。

Is there any way that I can convert the strings into their proper types? 有什么方法可以将字符串转换为正确的类型? Or is their a better (but still simple) way of doing what I am trying to do? 还是他们做我想做的更好(但仍然很简单)的方法?

Any help would be much appreciated. 任何帮助将非常感激。 Thanks! 谢谢!

"Or is their a better (but still simple) way of doing what I am trying to do?" “或者他们是我尝试做的更好(但仍然很简单)的方式?”

Option 1 One easy and good way is to use a dictionary in a python file just do an import. 选项1一种简单而有效的方法是仅在导入时在python文件中使用字典。

myConfig.py myConfig.py

cfg={'a':"hello", 'b':123, 'c':[4,5,6]}

In your code: 在您的代码中:

from myConfig import *
print cfg['a']

You can also use indvidual variables instead of dictionary and do the same. 您也可以使用单个变量而不是字典并执行相同的操作。

Option 2 选项2

If you don't want a python file you can read any other file and use exec to executing the command line by line. 如果您不想要python文件,则可以读取任何其他文件,并使用exec逐行执行命令行。 Docs here: https://docs.python.org/2/reference/simple_stmts.html#exec 此处的文档: https : //docs.python.org/2/reference/simple_stmts.html#exec

You can use execfile but I believe it is discontinued in versoin 3.x Docs here: https://docs.python.org/2/library/functions.html#execfile 您可以使用execfile但我相信它在versoin 3.x Docs中已停产: https ://docs.python.org/2/library/functions.html#execfile

Option 3 选项3

You can also use other ways: 您还可以使用其他方式:

  1. Python ConfigParser: https://docs.python.org/2/library/configparser.html Python ConfigParser: https ://docs.python.org/2/library/configparser.html
  2. YAML files: http://pyyaml.org/wiki/PyYAMLDocumentation YAML文件: http : //pyyaml.org/wiki/PyYAMLDocumentation
  3. XML files: See this for an example: parsing XML configuration file using Etree in python XML文件:参见示例: 使用python中的Etree解析XML配置文件

Here is one way, using ast.literal_eval : 这是使用ast.literal_eval一种方法:

import ast
def config_file(filename):
    result = {}
    with open(filename) as f:
        for line in f:
            line = line.split('=',1)
            result[line[0]] = ast.literal_eval(line[1].strip())
    return result

print config_file('cfg.txt')

You'll probably want more beef in the for loop, like ignoring blank lines, removing comments, etc. 您可能需要在for循环中添加更多牛肉,例如忽略空行,删除注释等。

Also note that this puts the data in a dict , and not into the vars() dict. 另请注意,这会将数据放入dict ,而不放入vars() dict中。 You should keep data out of your variable names . 您应该将数据放在变量名之外 If you do want to add your config variables to your namespace, you can still use my function like so: 如果确实要将配置变量添加到名称空间,则仍然可以像下面这样使用我的函数:

vars().update(config_file('cfg.txt'))

In addition to answers below, for simple data structures you can use json format and dictionaries or namedtuples: 除了下面的答案,对于简单的数据结构,您可以使用json格式和字典或namedtuple:

import json
from ast import literal_eval
from collections import namedtuple

json_vars = """{
    'a' : "hello",
    'b' : 123,
    'c' : [4,5,6]
}"""


print json_vars
from_json = literal_eval(json_vars)
# or:
# from_json = json.loads(json_vars)

variables = namedtuple('Vars', from_json.keys())(*from_json.values())

print variables
print variables.a
print variables.b
print variables.c

print variables._asdict()
d = dict(variables._asdict())
print d

print d['a']
print d.items()


as_json_again = json.dumps(d, indent=2)

print as_json_again

For more advanced objects, see pickle module. 有关更多高级对象,请参见pickle模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM