运行代码之间的Python计数器

时间:2014-12-27 22:27:44

标签: python text counter

我想通过使用此代码限制我打印到文本文件中的次数,每次运行下面的代码时,a被定义为零,我怎么能通过保存生成一个有效的计数器它在代码末尾的值,然后在下次运行代码时恢复其值?

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

谢谢你,谢谢。

2 个答案:

答案 0 :(得分:3)

怎么样......:

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)

与例如

def save_state(a):
    with open('saveit', 'w') as f:
        f.write(str(a))

def restore_state():
    try:
        with open('saveit', 'r') as f:
            a = int(f.read())
    except IOError:
        a = 0
    return a

...

答案 1 :(得分:0)

对于单个整数,它很难比纯文本文件简单。如果您想更多地参与 - 更多设置,不同的数据类型 - 您可以使用JSON(import json)或YAML(import yaml)或配置文件(import configparser)。

您需要定义默认设置(如果设置文件不存在,请使用默认值),从文件加载设置的功能,以及将设置保存到文件的功能。

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
你使用的

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()