Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save variable value in python

Tags:

python

Is there a way to SAVE the value of a variable (say an integer) in python? My problem involves calling (entering and exiting) multiple times the same python script (python file, not python function) which in the end creates a txt file. I'd like to name the txt files depending on the number of times the python code was called: txt1.txt,..., txt100.txt for example.

EDIT: The question is not related with the SAVE parameter in fortran. My mistake.

like image 758
jpcgandre Avatar asked Nov 21 '25 17:11

jpcgandre


1 Answers

Not really. The best you can do is to use a global variable:

counter = 0
def count():
    global counter
    counter += 1
    print counter

An alternative which bypasses the need for the global statement would be something like:

from itertools import count
counter = count()
def my_function():
    print next(counter) 

or even:

from itertools import count
def my_function(_counter=count()):
    print next(_counter)

A final version takes advantage of the fact that functions are first class objects and can have attributes added to them whenever you want:

def my_function():
    my_function.counter += 1
    print my_function.counter

my_function.counter = 0 #initialize.  I suppose you could think of this as your `data counter /0/ statement.

However, it looks like you actually want to save the count within a file or something. That's not too hard either. You just need to pick a filename:

def count():
    try:
        with open('count_data') as fin:
            i = int(count_data.read())
    except IOError:
        i = 0
    i += 1
    print i
    with open('count_data','w') as fout:
        fout.write(str(i))
like image 52
mgilson Avatar answered Nov 23 '25 05:11

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!