2017-03-08 49 views
-3

所以我想在我的遊戲的python排行榜上,我試圖寫入1個文件中的信息到另一個文件。我現在有代碼:從1個文件寫入到另一個python

playerName = "Luke" 
playerScore = 12 

def functionHighscore(): 
    highscore = open('H:\Year 13\Computer science\leaderboard\practice.txt','r') 


    for eachline in highscore: 

     ply_code,ply_name,ply_score=eachline.split(",") 

     if playerName == ply_name: 
      ply_score = playerScore 

     print(ply_name, ply_score) 

    functionUpdatehighscore(highscore) 

def functionUpdatehighscore(highscore): 
    updatehighscore = open('H:\Year 13\Computer science\leaderboard\updatepractice.txt','w') 
    for eachline in highscore: 
     print(eachline) 

functionHighscore() 

,並將其與錯誤出現:

syntaxError (unicode error) 'Unicodeescape' codec cant decode bytes in position 39-40: truncated \uXXXX escape (line21, offset 27): 'updatehighscore = open('H:\Year 13\Computer science\leaderboard\updatepractice.txt','w') 
+0

使用原前綴:'R'H:\年13 \計算機科學\排行榜\ updatepractice.txt''或'\ u'被視爲Unicode轉義。 –

+0

將您的路徑存儲爲變量.i.e'location1 ='H:\ Year 13 \ Computer science \ leaderboard \ practice.txt''和'location2 ='H:\ Year 13 \ Computer science \ leaderboard \ updatedpractice.txt''。用這些'highscore = open(location2.encode('unicode-escape'),'r')'',updat ehighscore = open(loca tion2.encode('unicod e-escape')',' W')'。如果您使用的是Python 2,請使用'string-escape'而不是'unicode-escape' – mondieki

回答

0

嘗試使用原始字符串:

highscore = open(r'H:\Year 13\Computer science\leaderboard\practice.txt','r') 

updatehighscore = open(r'H:\Year 13\Computer science\leaderboard\updatepractice.txt','w') 

使用帶有文件路徑的原始字符串總是有幫助的,otherwi每個\必須被轉移到\\

+0

非常感謝,它的工作原理:) –

+0

我可以問爲什麼我必須這樣做嗎? –

+0

添加了簡短說明(將'\'轉義爲'\\') –

-1

你需要在r(raw)前面加上路徑字符串,否則Python會將反斜線解釋爲特殊字符的轉義。

例如

r'H:\Year 13\Computer science\leaderboard\practice.txt' 
相關問題