I have a text file, params.txt
say, that is of the following form (ignore the colour formatting, this is a plain text file not python code):
Lx = 512 Ly = 512
g = 400
================ Dissipation =====================
nupower = 8 nu = 0
alphapower = -0 alpha = 0
================ Timestepping =========================
SOMEFLAG = 1
SOMEOTHERFLAG = 4
dt = 2e-05
[...and so on]
i.e. the variables are separated by their values by =
, the values are a mixture of ints, floats, and scientific notation, there are sometimes two variable/value pairs on a line separated by a single space, and there are headings of the form
================ HeadingToBeDiscarded ================
In python, how do I read the text file, and automatically in my python script create the same variables and assign them the same values as are in the file?
The format of the file will be identical each time so brute forcing would be possible but I'm sure there's an elegant python/regex solution (but I'm new to python and have barely ever regexed!)
now if you want to (hardcode?) data in .txt
file to .py
file you should use something like this:
temp_list = []
with open("params.txt") as file:
while True:
line = file.readline()
line = line.strip()
value = line.split(' ')
for i, word in enumerate(value):
if word == '=':
var = f'{value[i-1]} = {value[i+1]}'
temp_list.append(var)
if not line:
break
with open('sets.py', 'w') as f:
f.write('\n'.join(temp_list))
this will create a new python file named sets.py
(you can change name) and store all values from text file to .py file. Now to use these values first make sure that sets.py
is in the same directory as your main python scipt and then do from sets import *
now you will be able to acces any of those values by just typing its name and it will be recognized. try it out