Я пытаюсь написать код, который зацикливается, если условие не существует.
Я работаю над началом программы, и я новичок в 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)».






Попробуй это:
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.")
Большое спасибо. Это заняло наименьшее количество кода и отлично сработало. Сначала я забыл path1=input(), и печать бесконечно зацикливалась. Было интересно. Еще раз спасибо!
Это можно легко сделать с помощью цикла 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. Часть кода, начинающаяся с «с», называется диспетчером контекста и используется для открытия файлов. Метод endwith проверит расширение файла.
Вы можете добиться этого с помощью рекурсивной функции, например:
# 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()
Возможный дубликат/связанный с запрашивать у пользователя ввод, пока он не даст правильный ответ?