views:

43

answers:

2

I am making a python program, and I want to check if it is the users first time running the program (firstTime == True). After its ran however, I want to permanently change firstTime to False. (There are other variables that I want to take input for that will stay if it is the first run, but that should be solved the same way).

Is there a better way then just reading from a file that contains the data? If not, how can I find where the file is being ran from (so the data will be in the same dir)?

+3  A: 

If you want to persist data, it will "eventually" be to disk files (though there might be intermediate steps, e.g. via a network or database system, eventually if the data is to be persistent it will be somewhere in disk files).

To "find out where you are",

import os
print os.path.dirname(os.path.abspath(__file__))

There are variants, but this is the basic idea. __file__ in any .py script or module gives the file path in which that file resides (won't work on the interactive command line, of course, since there's no file involved then;-).

The os.path module in Python's standard library has many useful function to manipulate path strings -- here, we're using two: abspath to give an absolute (not relative) version of the file's path, so you don't have to care about what your current working directory is; and dirname to extract just the directory name (actually, the whole directory path;-) and drop the filename proper (you don't care if the module's name is foo.py or bar.py, only in what directory it is;-).

Alex Martelli
A: 

It is enough to just create file in same directory if program is run first time (of course that file can be deleted to do stuff for first run again, but that can be sometimes usefull):

firstrunfile = 'config.dat'
if not  os.path.exists(firstrunfile):
    ## configuration here
    open(firstrunfile,'w').close() ## .write(configuration)
    print 'First run'
    firstTime == True
else:
    print 'Not first run'
    ## read configuration
    firstTime == False
Tony Veijalainen