Reputation: 179
In Python, I have a task to create a completely new file for storing high scores. The program should ask to enter your name, date and high score. Each value should be separated by a comma.
Here is my current code :
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()
I am having problems trying to separate each value by using a comma. What am I doing wrong? In the text file, the comma is not added, therefore all the values are next to eachother.
Thanks
Upvotes: 1
Views: 699
Reputation: 16711
Change your code like so, you just have a few minor errors:
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()
Upvotes: 0
Reputation: 9991
More compact version:
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(',')
with statement will automatically close the file.
Upvotes: 2