[英]How do I save data in a text file python
因此,我正在制作一個簡單的隨機數字游戲,即使在程序關閉並再次運行后,我也希望為玩家保留高分。 我希望計算機能夠詢問玩家的姓名,在文本文件中搜索姓名數據庫,並提高他們的高分。 然后,如果它們的名稱不存在,請在數據庫中創建一個名稱。 我不確定該怎么做。 我是一個菜鳥程序員,這是我的第二個程序。 任何幫助,將不勝感激。
這是隨機數游戲的代碼:
import random
import time
def getscore():
score = 0
return score
print(score)
def main(score):
number = random.randrange(1,5+1)
print("Your score is %s") %(score)
print("Please enter a number between 1 and 5")
user_number = int(raw_input(""))
if user_number == number:
print("Congrats!")
time.sleep(1)
print("Your number was %d, the computers number was also %d!") %(user_number,number)
score = score + 10
main(score)
elif user_number != number:
print("Sorry")
time.sleep(1)
print("Your number was %d, but the computers was %d.") %(user_number, number)
time.sleep(2)
print("Your total score was %d") %(score)
time.sleep(2)
getscore()
score = getscore()
main(score)
main(score)
編輯:我正在嘗試這樣做,它似乎正在工作,除了,當我嘗試用一個變量替換字符串時,它給出了一個錯誤:
def writehs():
name = raw_input("Please enter your name")
a = open('scores.txt', 'w')
a.write(name: 05)
a.close()
def readhs():
f = open("test.txt", "r")
writehs()
readhs()
為了使用python編寫文件,請執行以下操作:
file2write=open("filename",'w')
file2write.write("here goes the data")
file2write.close()
如果要讀取或追加文件,只需將“ r”或“ a”分別更改為“ w”
with open('out.txt', 'w') as output:
output.write(getscore())
像這樣使用with
是處理文件的首選方式,因為即使在出現異常時,它也會自動處理文件關閉。
另外,請記住要修復getscore()
方法,以便它並不總是返回0。如果您還希望它print
分數,請將print
語句放在return
之前。
首先,您應該清楚地提出問題,讓其他人理解。要將文本添加到文本文件中,您可以始終使用內置的open
功能。
>>> a = open('test.txt', 'w')
>>> a.write('theunixdisaster\t 05')
>>> a.close()
就是這樣。如果需要進一步的幫助,請嘗試此網站。 http://www.afterhoursprogramming.com/tutorial/Python/Writing-to-Files/
您也可以在游戲中使用for循環來打印所有分數。 自己嘗試一下,這會很有趣。
推薦方式
就像推薦的方式一樣使用它:
>>> with open('test.txt', 'w') as a:
a.write('theunixdisaster\t 05')
這樣就可以確定文件將關閉。
有變量
>>> name = sempron
>>> with open('test.txt', 'w') as a:
a.write('%s: 05' % name)
現在嘗試調用它。我使用的是python 3.4.2
。因此,如果遇到錯誤,請嘗試檢查所使用的python版本的字符串格式是否存在任何差異。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.