I am now relatively experienced in Python and Pygame for creating a few basic 2D graphical games. Now I want to be able to create a configuration file (config.cfg) so that I can permanently store settings and configurations for the game for things like window width and height and FPS count. The file should read vertically e.g.
FPS = 30
WINDOW_WIDTH = 1280
WINDOW_HEIGHT = 720
etc.
Obviously I need to be able to read (and create) this file from my game and also edit the values without touching the text labels. I have not touched on this stuff before although I have worked with using text files in Python so I need as much guidance as possible please. I am using Python 3.3 with Pygame 1.9 on Windows 8 Pro x64.
myConfig.cfg:
[info]
Width = 100
Height = 200
Name = My Game
Parsing in python:
import ConfigParser
configParser = ConfigParser.RawConfigParser()
configFilePath = os.path.join(os.path.dirname(__file__), 'myConfig.cfg')
configParser.read(configFilePath)
gameName = configParser.get("info","Name")
gameWidth = configParser.get("info","Width")
gameHeight = configParser.get("info","Height")
configParser.set('info', 'Name', 'newName')
config.write(configFilePath)
Explanation:
First we crate an instance of ConfigParser then we are telling the instance where the .cfg file is located, after just it's just reading.
The second part we handle the writing.
More information:
Config Parser from Docs
If you are looking for something more flexible try YAML and PyYAML
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With