Edit/read configuration text file within Python
Posted on 2007-12-04
I am trying to save/read a configuration file from within Python. Here is the situation I am in:
Currently, I am working on a script under Linux, in Python. I want to be able to save some configuration to a file like config.txt. This file would be located in a location similar to:
I also want the Python script to be able to be run from anywhere, eg, from the Desktop, home folder, or any other folder and save and read from the same location.
After some research, I have found that I can use the following code to open a file: f = open("config.txt","w")
The problem is that I can't specify a location. The following code:
f = open("~/.[program]/config.txt","w")
does not work, because it does not accept ~/
I cannot give a relative address (like .[program]/config.txt if the script was located in the home directory), as the script could be run from anywhere within the users home directory.
I cannot give a full address (not that I am aware of), because I need to have a dynamic username for the [user] field in "/home/[user]/.[program]/config.txt", and I am not aware of how to get the current users username, if it is possible.
What is the best way to save and read the configuration file, if the python script is located anywhere within the users home directory?