简体   繁体   English

FileNotFoundError Try and except 似乎不起作用

[英]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.您可以将 with 块移出循环或将其放在 else 块下。 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:首选将需要额外检查a (或者如果y.lower != 'y'在开始时更简单的return 。我认为以下方法更干净:

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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