2015-02-10 73 views
1

在Python中,我有一個任務來創建一個用於存儲高分的全新文件。該計劃應要求輸入你的姓名,日期和高分。 每個值應該用逗號分隔。Python - 將數據追加到文件中,Line.split

這裏是我當前的代碼:

Name=input('What is your name:') 
Date=input('What is the date:') 
Score=input('What was your high score:') 

myFile=open('Scores.txt','wt') 
myFile.write(Name) 
myFile.write(Date) 
myFile.write(Score) 
myFile.close() 

myFile=open('Scores.txt','r') 
line=myFile.readline() 
line=line.split(',') 
myFile.close() 
我有問題想用逗號分隔每個值

。我究竟做錯了什麼?在文本文件中,不會添加逗號,因此所有的值都是彼此相鄰的。

感謝

+1

你永遠不會將逗號寫入文件,唉! – 2015-02-10 21:10:28

+1

'myFile.write(「{},{},{}」。format(Name,Date,Score))'或更好,請使用[this](https://docs.python.org/2/library/ csv.html) – alfasin 2015-02-10 21:11:52

+0

文件模式應該是'w +'not'wt'。 – 2015-02-10 21:12:32

回答

0

更改您的代碼像這樣,你只是有一些小的錯誤:

Name=input('What is your name:') 
Date=input('What is the date:') 
Score=input('What was your high score:') 

myFile=open('Scores.txt','w+') # w+ not wt 
myFile.write(Name + ',') 
myFile.write(Date + ',') 
myFile.write(Score) 
myFile.close() 

myFile=open('Scores.txt','r') 
line=myFile.readline() 
line=line.split(',') # commas need to be added to split 
myFile.close() 
2

更緊湊:

Name=input('What is your name:') 
Date=input('What is the date:') 
Score=input('What was your high score:') 

with open('Scores.txt','w+') as f: 
    f.write(','.join([Name, Date, Score])) 

with open('Scores.txt','r') as f: 
    for line in f: 
     values = line.split(',') 

聲明將自動關閉文件。