1

I have a file called options.txt:

fullscreen = False
screen_width = 1920
screen_height = 1080
walk_up = 119
walk_down = 115
walk_left = 97
walk_right = 100
inventory = 9
jump = 32
collect_item = 101

It contains some information that I want to be able to set variables to. For example, this line is creating a window, and I want to be able to set these arguments to the value from the options.txt file. How can I do this?

(pseudo code):

settings = open("options.txt").read()
pg.display.set_mode((settings.screen_width, settings.screen_height), pg.RESIZABLE)

Or make checks:

if not settings.fullscreen:
    pass
Hydra
  • 373
  • 3
  • 18
  • See also [What's the best practice using a settings file in Python?](https://stackoverflow.com/q/5055042/4518341) – wjandrea May 27 '20 at 22:21
  • You can use YAML. It's easy to load into a dict and dump to yaml using yaml's library. Take a look: https://stackabuse.com/reading-and-writing-yaml-to-a-file-in-python/ – Raphael May 27 '20 at 22:22

1 Answers1

1

If you used JSON or YAML this would be easier, but considering the format of your file it should be a breeze to parse. Here is the quick and dirty of what you need.

import re

data = 'val1=1\nval2=true\nval3=somename'
lines = data.split('\n')

oper = re.compile('[\s]*=[\s]*')
num = re.compile('^[0-9]*$', re.M)
bool = re.compile('^(true|false)$', re.I | re.M)

settings = dict()

for n in lines:
    name, value = oper.split(n)
    if num.match(value):
        settings[name] = int(value)
    elif bool.match(value):
        settings[name] = value.lower() == 'true'
    else:
        settings[name] = value

print(settings)
# {'val1': 1, 'val2': True, 'val3': 'somename'}

There are more things you can do here. For instance instead of splitting all the data on lines, you could just read the file line by line. If you need to add more types (like float) you will need to write more regexps and include them in your parse conditions.

OneMadGypsy
  • 4,640
  • 3
  • 10
  • 26