Record#
- Today, continue learning file operations for file reading using the open(url, r) function.
- Use the read() function to get 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. Since the last line in the file is empty, use if contents == "" to break the loop.
- Today's exercise is to read data from high.score, determine which line has the highest number, and then output it.
- Using if value == "" to check for empty is not a good way, 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}")