簡體   English   中英

運行代碼之間的Python計數器

[英]Python counter between running code

我想通過使用此代碼來限制我打印到文本文件中的次數,每次我運行下面的代碼時,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

任何事情將不勝感激謝謝

關於什么...:

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

...?

對於單個整數,很難比純文本文件更簡單。 如果您想參與其中-更多設置,不同數據類型-您可以使用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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM