2017-05-04 81 views
0
def highscore(): 
    var = input("Please enter your nickname ") 
    ### And then i want this to be saved within the txt file on my desktop. 
    self.highscoreList.sort() #Sorterar listan man har med highscores (behövs ju inte om den redan är sorterad) 
    if playerScore > self.highscoreList[0]: #Om spelarens poäng högre än lägsta highscore 
     self.highscoreList[0] = playerScore #Byt ut det lägsta mot spelarens 
      #Nånting sånt här iallafall... 
     file = read("/Volumes/me SSD/Users/me/Desktop/Python/highscore.txt", "w") 
     for highscore in self.highscoreList: #Sen skriva till fil! 
      file.write(highscore) #Skriver highscores till filen, en för varje rad 
      file.write("hej") #I have even tried to just have \n 
    file.close() 

我已經在Python 3.5.2做了一個遊戲(minesweaper),當玩家已經玩過的遊戲,我希望他/她進入他/她的暱稱,以便它會將高分保存在桌面上的(txt)文件中。不能我的文件保存在一個txt文件

我試圖做到這一點,但它不會在txt文件中保存任何東西。玩家也沒有得到輸入來寫下他/她的暱稱。

我試圖讓file.close()有或沒有循環,但它沒有工作。

+1

你的意思是'打開()'文件而不是'read()'?如果'if'中的條件返回false,'if'可能會導致問題 – kuro

+1

縮進的關閉 – ForceBru

回答

1
use this 

     try: 
     fil = open("/Volumes/Melinas SSD/Users/Melina/Desktop/Python/melinas.txt", "w") 
    except: 
     print('the file cannot be opened') 

for highscore in self.highscoreList: 


print('hello') 
      file.write(highscore) 
      file.write("hej") 
+0

我試過這個,但它不起作用。 :/ –

+0

更改爲別的= open(「/ Volumes/me SSD/Users/me/Desktop/Python/highscore.txt」,「w」) file is reserved關鍵字 – Exprator

+0

試過:S –

0

如何寫的內容在文件

使用open()方法寫在文件內容,不閱讀()和read()沒有內置方法。

演示:

>>> fp = open("mytest.txt", "w") 
>>> fp.write("I am Python Developer.") 
>>> fp.write("\nI Love Coding.") 
>>> fp.close() 

注意

請勿使用都是用Python即關鍵字保留變量名。 A file是內置關鍵字。

>>> file 
<type 'file'> 

你定義playerScore變量?

+1

這是正確的。也可以使用上下文管理器,如 與打開(path_to_file)作爲f: f.write('Something') – gonczor

+0

我試圖將所有此文件更改爲fil,並閱讀以打開,但它不會打印:'( –

+0

@ soetirl:需要你的代碼,你可以再次與我們分享嗎? –

1

在您可以讀取或寫入文件之前,您必須使用Python內置的open()函數打開它。該函數創建一個文件對象,該對象將用於調用與其關聯的其他支持方法。這裏是語法 file object = open(file_name [, access_mode][, buffering])

file = open("/Volumes/me SSD/Users/me/Desktop/Python/highscore.txt", "w") 
+0

它也不會工作:( –

2

在Python 3,規範的方式來寫一個文件是如

with open("output.txt", "w") as output_file: 
    print("my output", file=output_file) 

注意,我開了一個with塊內的文件,所以它是自動關閉,並且我通過將關鍵字參數file提供給Python 3的print函數打印到該文件。

您可以先導入它使用在Python 2擴展print功能,

from __future__ import print_function 

,然後調用print如常。

+0

Python 2也支持這個 – gonczor

+0

不,它不是,打印不是Python 2中的函數,它是一個關鍵字,你可以導入打印功能,從未來等,雖然 – innisfree

+0

我thougt你用'寫'不打印。對不起,我還是半清醒 – gonczor