简体   繁体   中英

FileNotFoundError Try and Except seems to not be working

 def make_sender(self):
        a = False
        y = input("Make sender (Y/N)?")
        if y.lower() == "y":
            a = True
        while a == True:
            s = input("Enter folder name : ")
            t = input("Enter profile name: ")
            try:
                p = os.getcwd()+("\profiles")
                d = os.path.join(p, s,t)
                with open(d+".txt","w") as f:
                    print(">>> Opened ")
            except FileNotFoundError:
                print(">>> File not found ")
            
            with open(d+".txt","w") as f:
                temp = input("Full Name: ")
                temp = temp.title()
                f.write(temp+"\n")

                temp = input("House Number: ")
                f.write(temp+"\n")

                temp = input("Street Name : ")
                f.write(temp+"\n")
                
                temp = input("Postcode    : ")
                f.write(temp+"\n")

                temp = input("Email       : ")
                f.write(temp+"\n")
            a = False

Thought that my code would keep running until correct data is entered. Think my try and except is built wrong. I've got the correct except code but think the indents or something is wrong.

You can either move your with block out of loop or put it under else block. First choice will require additional check for a (or simpler return at the beginning if y.lower != 'y' . I think the following approach is cleaner:

 def make_sender(self):
        y = input("Make sender (Y/N)?")
        while y.lower() == 'y':
            s = input("Enter folder name : ")
            t = input("Enter profile name: ")
            try:
                p = os.getcwd()+("\profiles")
                d = os.path.join(p, s,t)
                with open(d+".txt","w") as f:
                    print(">>> Opened ")
            except FileNotFoundError:
                print(">>> File not found ")
            else:
                with open(d+".txt","w") as f:
                    temp = input("Full Name: ")
                    temp = temp.title()
                    f.write(temp+"\n")

                    temp = input("House Number: ")
                    f.write(temp+"\n")

                    temp = input("Street Name : ")
                    f.write(temp+"\n")
                
                    temp = input("Postcode    : ")
                    f.write(temp+"\n")

                    temp = input("Email       : ")
                    f.write(temp+"\n")
                    
                break

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