Parse key value pairs in a text file

后端 未结 6 1328
無奈伤痛
無奈伤痛 2020-11-28 09:31

I am a newbie with Python and I search how to parse a .txt file. My .txt file is a namelist with computation informations like :

myfile.txt

6条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 09:56

    I suggest storing the values in a dictionary instead of in separate local variables:

    myvars = {}
    with open("namelist.txt") as myfile:
        for line in myfile:
            name, var = line.partition("=")[::2]
            myvars[name.strip()] = float(var)
    

    Now access them as myvars["var1"]. If the names are all valid python variable names, you can put this below:

    names = type("Names", [object], myvars)
    

    and access the values as e.g. names.var1.

提交回复
热议问题