Python FileNotFoundError Try和Except似乎不起作用

Python FileNotFoundError Try和Except似乎不起作用,python,while-loop,try-except,Python,While Loop,Try Except,我认为我的代码会一直运行,直到输入正确的数据。我认为我的尝试是错误的。我得到了正确的代码,但我认为缩进或其他地方有问题。您可以将with块移出循环,或将其置于else块下。如果y.lower!='是的。我认为以下方法更干净: def make_sender(self): a = False y = input("Make sender (Y/N)?") if y.lower() == "y":

我认为我的代码会一直运行,直到输入正确的数据。我认为我的尝试是错误的。我得到了正确的代码,但我认为缩进或其他地方有问题。

您可以将with块移出循环,或将其置于else块下。如果y.lower!='是的。我认为以下方法更干净:

 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

尽管出现错误,您仍然尝试打开该文件逐行查看代码。每次看到复合语句时,都要考虑下一行是否应该是它的一部分。如果没有,请取消记录下一行和以下行。在未找到打印文件后,继续打开文件,即使出现错误。你可能是想把整个缩进。。。少挡一层。此外,您应该养成使用有意义的变量名的习惯,所有这些一个字母的变量都会使代码毫无用处地更难阅读。
 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