2017-01-22 11 views
-2

マイコード:Python、私はリーダーボードを作ろうとしていますが、誰かが私を助けることができるテキストファイルに保存されませんか?

leaderboard code

ファイル "leaderboard.txtは" ブランクのまま。それらは両方とも同じフォルダに保存されます。

コード:コードの収縮したバージョンで

print ("1: Enter new high score.", "\n","2: Display scores.", "\n","3: Clear scores", "\n","4: Quit") 
    choice = input("") 
    while choice != "4": 
     file = open("leaderboard.txt", "w") 
     if choice == "1": 
      score = input("what was your score") 
      date = input("whats the date") 
      name = input("whats your name")  
      file.write(name + ", "+date+", "+score+"\n") 
      file.close() 
      choice = input("choice") 
     elif choice == "2": 
      f = open("leaderboard.txt", "r") 
      file_contents = f.read() 
      print(file_contents) 
      f.close() 
      choice = input("choice") 

     elif choice == "3": 
      open("leaderboard.txt", 'w').close() 
      print("erased") 
      choice = input("choice") 

print("program quit")  
file.close() 
+1

*質問自体に[MCVE] *入れてください。レビュー[尋ねる]。 – jonrsharpe

+0

スクリーンショットの代わりに質問にあなたのコードをコピーしてください – shash678

+0

あなたが開いている/切り捨てて書いてからファイルから読んでみてください! –

答えて

0

見て:あなたは、最初のファイルを切り捨てている

while choice != "4": 
    file = open("leaderboard.txt", "w") 
    ... 
    elif choice == "2": 
     f = open("leaderboard.txt", "r") 

、それから読み取るしようとしています。

期待どおりのデータが得られません。

修正:ファイルが場合1にのみ書面で開かれているように、このような行を入れ替える:

if choice == "1": 
     file = open("leaderboard.txt", "w") 
+0

ありがとう、私はそれを私はちょうどif文の中でファイルを開く必要がありました:) – Billibob

0

私は、コードを実行して作られたテキストファイルは空白ではありません!

ファイルが読み込まれる前に上書きされているため、空白だと思ったのはその理由です。

ここにいくつかの修正されたコードがあります。

print ("1: Enter new high score.", "\n","2: Display scores.", "\n","3: Clear scores", "\n","4: Quit") 

choice = input("") 

while choice != "4": 

    try: 

     open("leaderboard.txt", "r") #Tests if the file exists 

    except FileNotFoundError: 

     open("leaderboard.txt", "w") #If not creates the file 

    if choice == "1": 

     score = input("what was your score") 

     date = input("whats the date") 

     name = input("whats your name") 

     file.write(name + ", "+date+", "+score+"\n") 

     file.close() 

     choice = input("choice") 

    elif choice == "2": 

     f = open("leaderboard.txt", "r") 

     file_contents = f.read() 

     print(file_contents) 

     f.close() 

     choice = input("choice") 

    elif choice == "3": 

     open("leaderboard.txt", 'w').close() 

     print("erased") 

     choice = input("choice") 

print("program quit") 

file.close() 

〜ジョス

関連する問題