Link to home
Start Free TrialLog in
Avatar of dh-s
dh-s

asked on

Edit/read configuration text file within Python

Hello,

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:
    /home/[user]/.[application]/config.txt
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?

Thanks!
ASKER CERTIFIED SOLUTION
Avatar of pepr
pepr

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pepr
pepr

You might also be interested in Python standard module ConfigParser -- see http://docs.python.org/lib/module-ConfigParser.html
Avatar of dh-s

ASKER

Thanks. "os.getenv('HOME')" was all I needed/was missing from the code I had before!

Also, thanks for the suggestion of ConfigParser, I will have a look at that when larger configuration files are needed (currently, I am only storing a few lines of text)