Python 3 for循环不破坏

时间:2018-06-19 06:00:13

标签: python-3.x loops for-loop

我在使用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()

2 个答案:

答案 0 :(得分:1)

你的问题不在于try / except或while / break的使用。 看一下Exception变量' 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

答案 1 :(得分:0)

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