Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
71 views
in Technique[技术] by (71.8m points)

Open a file in read mode and add functions (Python)

I wrote a python program to create an output file with the filename scores.txt, asked the user to enter test scores (-10 to end) of a class, and wrote them to the file. The program then should open this file, read scores from the file to display letter grade for each score. This will be done by creating a function called 'display_letter' and will classify each score as following: If 90> then A, if 80> then B, etc.

Below is my code to create scores.txt, how can I open this file with the described function above?

def main():
    outfile=open('scores.txt','w')
    score=int(input('Enter the scores (-10 to stop):'))
    
    while score !=-1:
        outfile.write(str(score)+ '
')
        score=int(input('Enter the scores (-10 to stop):'))
    
    outfile.close()
    print('Data is written')
main()
question from:https://stackoverflow.com/questions/65896261/open-a-file-in-read-mode-and-add-functions-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To read, you open the file you have written in a similar way as before, except you use 'r' instead of 'w'. Then you you iterate through each line of your newly-read data, strip the newline characters, and evaluate the number written on each line.

data = open('scores.txt', 'r')
for line in data:
    grade = line.rstrip("
")
    if int(grade) >= 90:
        print(grade, "A")
    elif int(grade) >= 80:
        print(grade, "B")
    elif int(grade) >= 70:
        print(grade, "C")
    elif int(grade) >= 60:
        print(grade, "D")
    else:
        print(grade, "F")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...