简体   繁体   中英

Python - Appending data to a file, Line.split

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

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM