如何在 python 中创建一个循环,使 returns 达到先前的条件

How to create a loop in python that returns to a previous condition

我正在尝试编写一个在条件不存在时循环返回的代码。

我正在编写一个程序的开头,我对 python 还很陌生。我希望我的代码检查文件是否有效,是否继续下一步,是否请求文件的新路径。关于最好的方法有什么想法吗?我也想检查文件类型是否正确,但没有找到与我需要的代码类似的代码。但我认为最主要的是让它循环。

现在我只是在它之后结束 returns 无论文件是否被检索到。我可以再次复制并粘贴 exists 语句,但我知道必须有更好的方法来做到这一点。任何帮助将不胜感激。

# Imports OS module to allow interaction with underlying operating system
import os
# Imports time functions
import time

# Greet the user
print ("Welcome to Project Coded Phish.")
# Ask user for the path to the text file they would like to use
print ("Please provide a valid path to the chat log text (.txt) file.")
#save the path from the user input
path1 = input ()
exists = os.path.isfile(path1)
# if the file can be found
if exists:
    print ("File was successfully retrieved.")
# if it isn't found
else:
    print ("Please provide a valid path to the chat log text (.txt) file.")
    path1 = input ()

如果找到路径,它会打印正确的单词。它只打印 "Please provide a valid path to the chat log text (.txt) file."

试试这个:

path1 = input ()
while not os.path.isfile(path1):
    print ("Please provide a valid path to the chat log text (.txt) file.")
    path1 = input ()
print ("File was successfully retrieved.")

这可以通过 while 循环轻松完成:

while True:
    exists = os.path.isfile(path1)
    # if the file can be found
    if exists:
        print ("File was successfully retrieved.")
        # since condition is met, we exit the loop and go on with the rest of the program
        break
    # if it isn't found
    else:
        print ("Please provide a valid path to the chat log text (.txt) file.")
        path1 = input ()

你可以试试

import os

def ask_for_filepath():
    input_path = input("Please provide a valid path to the chat log text (.txt) file.")
    return input_path

input_path = ask_for_filepath()

while os.path.isfile(input_path) is False:
    input_path = ask_for_filepath()

试试这个:

while True:
    path1 = input()
    exists = os.path.isfile(path1)
    if exists and path1.endswith('.txt'):
        print("File was successfully retrieved.")
        with open(path1) as file:
            # do something with file
            break
    else:
        print("Please provide a valid path to the chat log text (.txt) file.")

While循环会一直循环直到break语句。以 'with' 开头的部分代码称为上下文管理器,用于打开文件。 endswith 方法将检查文件的扩展名。

您可以使用递归函数实现此目的,如下所示:

# Imports OS module to allow interaction with underlying operating system
import os
# Imports time functions
import time

# Greet the user
print ("Welcome to Project Coded Phish.")
# Ask user for the path to the text file they would like to use
print ("Please provide a valid path to the chat log text (.txt) file.")
# if the file can be found
def check():
    path1 = input ()
    exists = os.path.isfile(path1)
    if exists:
        print ("File was successfully retrieved.")
        return
    # if it isn't found
    else:
        print("file not found")
        check()

check()