Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse key value pairs in a text file

Tags:

python

file

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

var0 = 16
var1 = 1.12434E10
var2 = -1.923E-3
var3 = 920

How to read the values and put them in myvar0, myvar1, myvar2, myvar3 in python?

like image 397
Vincent Avatar asked Sep 01 '25 22:09

Vincent


1 Answers

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.

like image 184
Lauritz V. Thaulow Avatar answered Sep 03 '25 13:09

Lauritz V. Thaulow