首页 > 解决方案 > Python 3 for 循环不中断

问题描述

我遇到以下问题,而 True 代码块。当我运行它时,它会很好地创建文件夹,但是会触发“文件名错误或不存在”。消息并且程序返回询问“用于创建文件夹的文件的名称”。它似乎一遍又一遍地重新启动代码块,即使它创建的文件很好但永远不会跳出循环?我是编程新手,并试图在编码方面做得更好,因此非常感谢任何帮助。如果那里已经有关于此的帖子,我提前道歉,但我在发布之前尝试搜索但没有运气。谢谢

while True:
    try:
        file = input("Name of file to be used for folder creation. ")
        if os.path.isfile(file):
            print("Successful")
            with open(file, "r") as f: # This line down to the os.mkdir line, opens a file that user selects and makes folders based on the list of words inside, -
                for line in f:         # and strips off the white spaces before and after the lines.
                    os.mkdir(line.strip())
                break   # This block of code from "with open" line is NOT working correctly as it will create the folders, but will not break out of the loop and keeps asking for the name of the file to use.
        else:
            raise Exception
    except Exception as e:
        print("File name wrong, or file does not exist. ")
        time.sleep(3)
        cls()

标签: python-3.xloopsfor-loop

解决方案


您的问题不在于使用 try/except 或 while/break。看一下异常变量“e”。这真的是您在第 11 行抛出的异常吗?

您可以在第 13 行之前添加这样的行:

print(e.__str__())

,并找出问题所在。

(在我的情况下,要创建的文件夹已经存在)

因此,也许您可​​以定义自己的异常类并捕获一个。例如:

class WTFException(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)
while True:
    try:
        file = input("Name of file to be used for folder creation. ")
        if os.path.isfile(file):
            print("Successful")
            with open(file, "r") as f: # This line down to the os.mkdir line, opens a file that user selects and makes folders based on the list of words inside, -
                for line in f:         # and strips off the white spaces before and after the lines.
                    os.mkdir(line.strip())
                break   # This block of code from "with open" line is NOT working correctly as it will create the folders, but will not break out of the loop and keeps asking for the name of the file to use.
        else:
            raise WTFException
    except WTFException as e:
        print("File name wrong, or file does not exist. ")
        time.sleep(3)
        cls()
    except Exception as ex:
        print('Oops') # Do something else here if you want

推荐阅读