In: Computer Science
Using Python.
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 code that deletes the record
containing “John Perz”as the student name.
This the code i have so far but it's not working:
import os
def main():
found=False
search='John Perz'
student_file = open('student.txt','r')
temp_file = open('temp_students.txt','w')
name=student_file.readline()
score=''
while name !='':
score=student_file.readline()
name=name.rstrip('/n')
score=score.rstrip('/n')
if name !=search:
temp_file.write(name+'/n')
temp_file.write(score+'/n')
else:
found=True
name=student_file.readline()
student_file.close()
temp_file.close()
os.rename('temp.text','student.text')
if found:
print("The record was deleted")
else:
print("Record not found")
main()
Short Summary:
Implemented the program as per requirement
Attached source code and sample output
**************Please do upvote to appreciate our time.
Thank you!******************
Source Code:
def main():
with open("C:\\Users\\asus\\student.txt") as f:
lines = f.readlines()
for ind, line in enumerate(lines):
if line.startswith("John Perz"):
lines[ind] = ""
with open("C:\\Users\\asus\\student.txt","w") as f:
f.writelines(lines)
main()
Code Screenshot:
Output:
Input file:
OutputFile:
**************Please do upvote to appreciate our time.
Thank you!******************