【问题标题】:Python 3 for loop not breakingPython 3 for 循环不中断
【发布时间】:2018-06-19 06:00:13
【问题描述】:

我遇到了以下 while 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.x loops for-loop


    【解决方案1】:

    您的问题不在于使用 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
    

    【讨论】:

    • 我试过你的建议,但它没有给我任何信息,它只是在执行后突然关闭。但是我添加了一行来打印异常,现在它显示“[WinError 3] 系统找不到指定的路径:''”。我很难理解为什么会这样,因为它每次都可以完美地创建文件夹,它只是没有爆发它一直重复开始?如果它找不到指定的路径,它如何创建文件夹?谢谢
    • 我想 [WinError 3] 发生在 os.mkdir(line.strip()) 行上。您是否尝试修改用于创建文件夹的文件?根据您的错误消息,其中可能有一个空行。
    • 调试很重要。也许在可能发生任何相关错误之前打印每个变量。此外,您可以使用 IDE 的调试器功能(如 PyCharm 或 VS Code)。在您要检查的行之前添加一个断点,让调试器在断点处停止,您可以在断点处检查您想要的每个断点。
    • 既然你提到了,我使用的文本文件顶部有 4 行文本,几个空行,然后下面有更多文本。这些空白行会导致该错误吗?谢谢
    • 好的,我刚刚对此进行了测试,并且确实出现了如果有任何空行,它会抛出此错误消息。使用相同的文件对其进行了测试,但删除了所有空白行,并且它完美无缺。谢谢
    【解决方案2】:

    我猜它正在创建您在初始文件中提到的一些文件夹,但是在最后创建一些文件时可能会出现一些错误,因为没有执行 break(os.mkdir 行中的异常(line.strip()))。您正在捕获异常,但循环不会中断。正如 Harper 提到的,总是在 except 块中打印异常。

    【讨论】:

    • 我尝试了 harper longs 的建议,但他没有回应,也没有给我任何信息,它只是在执行后突然关闭。但是我添加了一行来打印异常,现在它显示“[WinError 3] 系统找不到指定的路径:''”。我很难理解为什么会这样,因为它每次都能完美地创建文件夹,它只是没有爆发,它一直在重复开始?如果它找不到指定的路径,它如何创建文件夹?关于可能发生的事情以及如何解决此问题的任何想法。谢谢
    • 您确定文件末尾没有尾行吗?
    • 是的,我最近才这样做。这似乎解决了这个问题。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    • 2012-09-21
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多