2017-01-15 10 views
4

私のプログラムはスコアボードタイプのシステムを備えた基本的なTkinterゲームです。このシステムは、ユーザ名と各ユーザの試行回数をテキストファイルに保存します。Pythonはテキストファイルの特定の単語を編集します

たとえば、ユーザーが初めての場合、テキストファイルの最後に[joe_bloggs、1]という名前が付けられ、joe_bloggsはユーザー名、1は試行回数です。そのユーザーの初めての時では、それは1です。

私は '更新'するか、毎回1ずつ増分するために数字 '1'を変更しようとしています。このテキストファイルには、すべてのユーザー、つまり[Joe、1] [example1、1] [example2,2]がその形式で格納されます。事前に

write = ("[", username, attempts ,"]") 

if (username not in filecontents): #Searches the file contents for the username  
    with open("test.txt", "a") as Attempts:  
     Attempts.write(write) 
     print("written to file") 

else: 
    print("already exists") 
    #Here is where I want to have the mechanism to update the number. 

ありがとう:ここ

は、私が現在持っているコードです。

+0

@MYGz現在、それらはスペースで区切られています。ありがとう – lwatson

+0

あなたのユースケースについては、マイクのソリューションがより適切です。 – MYGz

答えて

3

簡単な解決策は、標準ライブラリのshelveモジュール使用して次のようになります。

import shelve 

scores = shelve.open('scores') 
scores['joe_bloggs'] = 1 
print(scores['joe_bloggs']) 
scores['joe_bloggs'] += 1 
print(scores['joe_bloggs']) 
scores.close() 

出力:

1 
2 

次のセッション:

scores = shelve.open('scores') 
print(scores['joe_bloggs']) 

出力:

"shelf"は、永続的な辞書的なオブジェクトです。 "dbm"データベースとの違いは、シェルフ内の値(キーではない)が本質的に任意のPythonオブジェクト(pickleモジュールが処理できるもの)であることです。これには、ほとんどのクラスインスタンス、再帰的データ型、および多くの共有サブオブジェクトを含むオブジェクトが含まれます。キーは普通の文字列です。あなたは常に、ユーザーがすでにあるかどうかを確認したくない場合は

username = 'joe_bloggs' 

with shelve.open('scores') as scores: 
    if username in scores: 
     scores[username] += 1 
     print("already exists") 
    else: 
     print("written to file") 
     scores[username] = 1 

:ご使用の場合に適応し

>>> dict(scores) 
{'joe_bloggs': 2} 

:あなたは辞書に全体のコンテンツを変換することができ

そこには、defaultdictを使用することができます。その後、あなただけのscores['scores'][user] += 1を記述する必要が

from collections import defaultdict 
import shelve 

with shelve.open('scores', writeback=True) as scores: 
    scores['scores'] = defaultdict(int) 

with shelve.open('scores', writeback=True) as scores: 
    for user in ['joe_bloggs', 'user2']: 
     for score in range(1, 4): 
      scores['scores'][user] += 1 
      print(user, scores['scores'][user]) 

出力::複数のユーザーと刻みで

username = 'joe_bloggs' 

with shelve.open('scores', writeback=True) as scores: 
    scores['scores'][user] += 1 

joe_bloggs 1 
joe_bloggs 2 
joe_bloggs 3 
user2 1 
user2 2 
user2 3 
まず、ファイルを作成します
+0

を参照してください。それはピクルスとどう違うのですか? – MYGz

+0

これは辞書のようなものです。 –

+0

このソリューションは、より簡単なIMOです。 – MYGz

0

よ標準ConfigParserモジュールを使用して単純なアプリケーション状態を維持できます。

関連する問題