Как создать цикл в Python, который возвращает к предыдущему состоянию - PullRequest
0 голосов
/ 22 мая 2019

Я пытаюсь написать код, который возвращается, если условие не существует.

Я работаю над началом программы и довольно плохо знаком с Python. Я хочу, чтобы мой код проверял, является ли файл действительным, переходит ли он к следующему шагу, если он не запрашивает новый путь к файлу. Есть идеи, как лучше всего это сделать? Я также хотел бы проверить, если тип файла правильный, но не нашел код, похожий на то, что мне нужно. Но главное, я думаю, что это зацикливается.

Прямо сейчас я просто заканчиваю после того, как возвращается, был ли файл получен или нет. Я мог бы снова скопировать и вставить существующие операторы, но я знаю, что должен быть лучший способ сделать это. Любая помощь будет оценена.

# 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 ()

Он печатает правильные слова, если путь был найден. Он просто печатает «Пожалуйста, укажите правильный путь к текстовому файлу журнала чата (.txt)».

Ответы [ 5 ]

3 голосов
/ 22 мая 2019

Попробуйте это:

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.")
1 голос
/ 22 мая 2019

Это легко сделать с помощью цикла 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 ()
0 голосов
/ 22 мая 2019

Этого можно добиться с помощью рекурсивной функции, например:

# 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()
0 голосов
/ 22 мая 2019

Попробуйте это:

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.")

В то время как цикл будет продолжать цикл до оператора break. Часть кода, которая начинается с «с», называется диспетчером контекста и используется для открытия файлов. Метод endwith проверит расширение файла.

0 голосов
/ 22 мая 2019

Вы можете попробовать

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()
...