1

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:

4
  • What exactly is the issue with the while loop? What do you want the while loop to do? Commented Aug 17, 2020 at 22:57
  • 1
    @arundeepchohan my idea is to keep entering student names if we hit the else section (the name is not in the file) i thought i would include my code in a while loop then break it if the name is found Commented Aug 18, 2020 at 1:46
  • 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 Commented Aug 18, 2020 at 2:00
  • @yedpodtrzitko thanks it worked now but the "else" also gets executed !!! Commented Aug 18, 2020 at 2:10

1 Answer 1

1

So one of my friends found out that I needed to reorganize my code and I missed out on some concepts. apparently when dealing with files like my case else and elif can not be used that way inside a while loop.

  1. replace can not be used in this matter and the result will not be saved anywhere so it won't be written on the file. using update is the better option since the files are read with csv.Dictreader.
  2. file will start searching from the top of the file, so elif will be executed as well if it was written that way and writrow was placed at the end of the code.

So in case anyone needed it, the fixed code that is completely functional is:

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)
    writer = csv.DictWriter(temp_file, fieldnames=fields, lineterminator='\r')
    writer.writeheader()
    while True:
        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:
                data.update({'Student Name':new_name})
                print(f'({old_name}) has been updated to ({data["Student Name"]})')
                result = True
            writer.writerow(data)
        if not result:
            print("This name is not in the file. Please enter a valid name")
        else:
            break
shutil.move(temp_file.name , f)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.