python - An external increment? -


i trying create file "varstore.dat" (that not exist prior running this) should contain value 0. every time execute script, want increment value 1.

so trying create file 1 time, read file, , rewrite(or overwrite) file upon each execution. however, problem each time run program, initialize 0 , output 1. trying rewrite varstore.dat , new value become old value next time execute script.

def get_var_value(filename="varstore.dat"):     open(filename, "a+") f:         val = int(f.read() or 0) + 1         f.seek(0)         f.truncate()         f.write(str(val))         return val  your_counter = get_var_value() print("this script has been run {} times.".format(your_counter)) 

you need f.seek(0) before val.

def get_var_value(filename="varstore.dat"):     open(filename, "a+") f:         f.seek(0)         val = int(f.read() or 0) + 1         f.seek(0)         f.truncate()         f.write(str(val))     return val 

the original code works in python 2. python2 opens file(in a+ mode) @ 0 whereas python3 opens @ end(hence "append" mode). appears reason it's different because python2 based on c's stdio.h: https://linux.die.net/man/3/fopen

http://bugs.python.org/msg229514


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -