在Python中,我有一项任务是创建一个用于存储高分的全新文件。该程序应要求输入您的姓名,日期和高分。 每个值应以逗号分隔。
这是我目前的代码:
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()
我在尝试使用逗号分隔每个值时遇到问题。我究竟做错了什么?在文本文件中,未添加逗号,因此所有值都是彼此相邻的。
由于
答案 0 :(得分: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(',')
with 语句会自动关闭该文件。
答案 1 :(得分: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()