简体   繁体   中英

How to use try, except to write a file

I am trying to write a function using try and except. I created a file named "file", which contains all student personal information. I want to print the personal information when I input a student name and write it in a new file called "new_file". If the input student name is not included in "file", I want to print "Name Not Found". Since this is an assignment, and I am required to use try blocks. Is there anyone could help? The following is my code.

enter image description here

find_info = input("Please input the student name that you want to search:")

def write_file():
    try:
        for student in student_list:
            if (find_info == student.name):
                print("Find Personal Information of:", student.name)
                with open("/Users/ada/Desktop/new_file.txt", "w") as new_file:
                    new_file.write("Name: " + student.name + ", Student_id: " + student.student_id \
                                   + ", College: " + student.college + ", Citizenship:" + 
                                   student.citizenship \
                                   + ", Phone_number:" + student.phone_number + ", Address:" 
                                   + student.address)
            print("\n")
            print("Student Personal Information Created")
            print("\n")
            break
    except:
        print("\n")
        print("Student Name Not Found")

You've written your code to check if the student name is what you are looking for before you do anything with it, which is good practice, If you want it to throw an exception, though. you have to let it break or break it yourself, In this case, your if (find_info == student.name): checks to see if it exists, but you never tell it what to do else: . I would suggest adding an else statement that will throw an exception [ raise NameError("Breaking my stuff!") ] that can then be caught by your except . In the spirit of homework assignments, I'll leave the exact placement up to you. :)

There are no exceptions thrown on your code, you could remove try..exept, but since you are required to have try and except, I recommend changing your if statement to assert (find_info == student.name) , which will throw an AssertionError if the clause does not evaluate to True . Another option is adding an else statement subsequent to your if statement and raise with an exception. hopefully this can be helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM