I'm not sure why, but the function that I'm using for another program won't break out of the "while" loop when it gets to the FileNotFoundError exception.
import os
def delete_file(file_to_delete):
try:
os.remove(file_to_delete)
print('file removed: ', file_to_delete)
result = True
except FileNotFoundError:
print("Error. File not found.")
result = False
while result == False:
if result == True: break
input("Please enter a valid filename: ")
os.remove(file_to_delete)
return result
Instead, remove the while loop and change your logic for it to work -
import os
def delete_file(file_to_delete):
result = False
while result == False:
try:
os.remove(file_to_delete)
print('file removed: ', file_to_delete)
result = True
except FileNotFoundError:
print("Error. File not found.")
file_to_delete = input('Please enter valid filename: ')
return result
result = False
while result == False:
if result == True: break
input("Please enter a valid filename: ")
The loop doesn't contain anything that would change the value of result
, so yes, this loop will run forever.
Also, the call to input()
is useless because you're not saving the result anywhere.
What you think about that logic?
import os
def delete_file(file_to_delete):
while not os.path.isfile(file_to_delete):
print("Error. File not found.")
file_to_delete = input("Please enter a valid filename: ")
os.remove(file_to_delete)
print('file removed: ', file_to_delete)
return True
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.