I would like to limit the amount of times I print into a text file by using this code, every time I run the code below, a is defined as zero, how would I be able to make a counter which works by saving its value at the end of the code, and then restores its value when the code is next run?
a = 0
if a < 3:
score = 5
with open('tom.txt','a') as fo:
fo.write('Tom: ')
fo.write(str(score))
fo.write("\n")
a = a + 1
Anything would be appreciated thank you
What about...:
a = restore_state()
if a < 3:
score = 5
with open('tom.txt','a') as fo:
fo.write('Tom: ')
fo.write(str(score))
fo.write("\n")
a = a + 1
save_state(a)
with eg
def save_state(a):
with open('saveit', 'w') as f:
f.write(str(a))
and
def restore_state():
try:
with open('saveit', 'r') as f:
a = int(f.read())
except IOError:
a = 0
return a
...?
For a single integer, it's hard to be simpler than a plain text file. If you want to get more involved - more settings, different data types - you could use JSON ( import json
) or YAML ( import yaml
) or a config file ( import configparser
).
You need to define default settings (if the settings file does not exist, use the defaults), a function to load settings from a file, and a function to save settings to a file.
import json
class Settings:
def __init__(self, settings_file, default_values):
self.settings_file = settings_file
self.default_values = default_values
self.load()
def load(self, load_file=None):
if load_file is None:
load_file = self.settings_file
try:
with open(load_file) as inf:
self.values = json.load(inf)
except FileNotFoundError:
self.values = self.default_values
def save(self, save_file=None):
if save_file is None:
save_file = self.settings_file
with open(save_file, "w") as outf:
json.dump(self.values, outf)
def __getattr__(self, key):
return self.values[str(key)]
def __setattr__(self, key, value):
if key in {"settings_file", "default_values", "values"}:
return super(Settings, self).__setattr__(key, value)
else:
self.values[str(key)] = value
return value
which you use like
state = Settings("my_settings.json", {"a": 0})
if state.a < 3:
score = 5
with open('tom.txt','a') as fo:
fo.write('Tom: ')
fo.write(str(score))
fo.write("\n")
state.a += 1
state.save()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.