【发布时间】: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