Record#
- Today, continue learning file operations for file reading using the open(url, r) function.
- Use the read() function to retrieve the contents of the file, usually assigning it to a variable.
- After obtaining the contents in a variable, use the close() function to close the file operation.
- Use the readline() function to read a line of data from the file.
- Use a while loop to read all the lines in the file. The last line in the file is empty, so if the content is equal to "", the loop can be exited by using break.
- Today's exercise is to read data from high.score, determine which line has the highest number, and then output it.
- The condition if value == "" is not a good way to check for emptiness. A better way is to use if not value.
CODE#
import time
print("🌟Current Leader🌟")
print("Analyzing high scores......")
time.sleep(2)
f = open("high.score", "r")
numinfo = 1
while True:
contents = f.readline().strip().split()
if not contents:
break
if int(contents[1]) > numinfo:
numinfo = int(contents[1])
numname = contents[0]
f.close()
print(f"Current leader is {numname} {numinfo}")