Modifying python variables based on config file entries

时间:2015-10-29 15:43:38

标签: python csv configparser

Relative Python newbie, and I'm writing a script that takes as its input a csv file, splits it into its constituent fields line-by-line and spits it out in another format. What I have so far generally works very well.

Each incoming csv line has specific fields that are read into variables 'txnname' and 'txnmemo' respectively. Before I write out the line containing these, I need to test them for specific string sequences and modify them as necessary. At the moment I have these tests hard coded into the script as follows

if ('string1' in txnname) and ('string2' in txnmemo):
    txnname = 'string3'
if 'string4' in txnname:
    txnname = 'string5 ' + txnmemo

'stringx' is being used here replacing the actual text I'd like to use.

What I'd really like to do is to remove the search strings, variable names and modifier strings from the script altogether and place them in a config file that already exists alongside the script and contains various parameters read into the script via ConfigParser. That way I won't have to modify the code every time I want to test a new condition. The 'hacky' way of doing this would seem to be using eval/exec in some combination on the literal Python statements read in from the config file, however just about everybody says that there is nearly always a better alternative to eval/exec. However I can't come up with what this alternative would be despite much research. I've read mention of using dictionaries somehow, but can't get my head round how this would work, especially on an 'If' statement with more than one condition to be tested (as above)

Any advice gratefully received.

3 个答案:

答案 0 :(得分:2)

有几个选择。

最简单的方法是创建一个全局config模块,并定义字符串变量和修饰符,并将其导入此模块。基本上,这会将所有这些变量集中到一个位置,因此当您需要修改时,只需更改config模块。

另一个选项是使用configparser,如您所述。在这种情况下,您需要创建一个INI file,格式如下所示。每个部分都有不同的部分和键。

<强> example.ini

[DEFAULT]
variable_to_access = value

[INPUT]
txnname_mod = string1
txnmemo_mod = string2

[MODIFY]
txnname_mod = string3
txnmemo_mod = string4

现在您可以读取INI文件并像字典一样访问变量。

<强>的Python

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
>>> config['INPUT']['txnname_mod']
string1

有关详细信息,请查看文档here

答案 1 :(得分:1)

创建配置文件并使用configparser非常简单易行https://docs.python.org/2/library/configparser.html。 configparser已经将所有内容都放入了字典中。 Convert ConfigParser.items('') to dictionary

从字典中检索值的方法非常简单,可能是最快的方法。

使用示例

renames = {"string1": "string3",
           "string2": "string3",
           "string4": "string5 " + txnmemo}

# new_value = renames[txnname] # raises KeyError if txnname not in renames
new_value = renames.get(txnname, txnname) # txname is the default value if txnname is not in renames

如果您使用的是configparser方法,那么您将无法将"string5 " + txnmemo创建为字典结果。对于这种情况,请将配置文件结果设为"string5 *unique_text*",然后替换该文本。

new_value = renames.get(txnname, txname).replace("*unique_text*", txnmemo)

我只是让配置文件尽可能简单

[Renames]
string1 = string3
string2 = string3
string4 = string5 *unique_text*

configparser

import configparser
config = configparser.ConfigParser(allow_no_value=True, inline_comment_prefixes=(";"))
config.optionxform = str # Prevents key case change
config.read('rename.ini')

with open("file.csv", "r") as file:
    for line in file:
        txnname, txnmemo = line.split(",")
        txnname = config["Renames"].get(txnname, txnname)
        txnname = txnname.replace("*unique_text*", txnmemo)

答案 2 :(得分:0)

You can indeed use ConfigParser to read from .cfg files. That way you can read and write data on the .cfg file using config.get() and config.write()