Homework Help: Questions and Answers: A file exists on the disk named students.txt. The file contains several records, and each record contains two fields:
(1) the student’s name, and
(2) the student’s score for the final exam.
Write a program to change the final exam mark of Julie to 100
Step by Step Answering
A Simple Python script that reads the file students.txt
, updates Julie’s score to 100, and then writes the updated content back to the file:
def update_julie_score(file_path):
# Read the file
with open(file_path, 'r') as file:
lines = file.readlines()
# Update Julie's score
updated_lines = []
for line in lines:
name, score = line.strip().split()
if name == 'Julie':
updated_lines.append(f'{name} 100\n')
else:
updated_lines.append(line)
# Write the updated lines back to the file
with open(file_path, 'w') as file:
file.writelines(updated_lines)
# Update the path to your students.txt file
file_path = 'students.txt'
update_julie_score(file_path)
Explanation:
- Read the file: The script opens the file in read mode and reads all lines into a list.
- Update Julie’s score: It iterates through each line, splits the line to get the student’s name and score. If the name is ‘Julie’, it updates the score to 100. The updated line is then added to a new list.
- Write the updated lines back to the file: The script opens the file in write mode and writes the updated lines back to the file.
You can place the students.txt
file in the same directory as the script or provide the correct path to the file.
Learn More: Homework Help