I'm trying to make a function that lets the user input a file name, an old string to replace, and a new string. I have a header in the file and it's made with another function in my project. My issue is that when I do an inspection and test the code it displays the results needed, but when I go check the file in my directory nothing has changed so the func is not working basically.
another thing is that the while loop is not working properly, and I can't figure out why !you'll understand by running the code.
I have started coding recently so this is stressing me out.
The function:
import csv
from tempfile import NamedTemporaryFile
import shutil
def update_student_name():
result = False
f = input('Enter the file name with the extension .csv : ')
temp_file = NamedTemporaryFile(mode= 'w' , delete=False)
fields = ['Student Name', 'Student Grade']
with open (f , 'r') as csv_file,temp_file:
reader = csv.DictReader(csv_file, fieldnames=fields)
writer = csv.DictWriter(temp_file, fieldnames=fields,lineterminator='\r')
while not result:
old_name = input('Enter the name you would like to update/correct: ').title()
new_name = input('Enter the new name: ').title()
for data in reader:
if data['Student Name'] == old_name:
print(data)
data['Student Name']=data['Student Name'].replace(data['Student Name'],new_name)
print(data)
# print(f'({old_name}) has been updated to ({new_name})')
result = True
elif data['Student Name'] != old_name:
print("This name is not in the file. Please enter a valid name")
writer.writerow(data)
shutil.move(temp_file.name , f)
The file I'm working on looks like this:

writer.writerow(data)happens only once after the loop is done, so you have to indent it more is it's inside the loop and it writes every row back into file