Why won't the function break out of this loop? - python

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

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.

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

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

Related

When input() is used as function argument, why does it run before main()

I have two functions
read_operator_rate_file(filename = 'test_scenarios.csv') &
get_input(phone_number_to_dial = input("enter phone number>> "))
In main I am calling them in order and the first function checks the condition for the CSV and may exit if there's any error. But, now when I put input function as the parameter for get_input function I am reading the prompt before the first function is being executed.
the code sample:
import csv
def read_operator_rate_file(filename = 'test_scenarios.csv'):
try:
with open(filename, newline='') as f:
# read each row as a list and store it in a list
operator_data = list(csv.reader(f))
operator_data.sort(key = lambda x:int(x[0]))
return operator_data
except FileNotFoundError as errorcode:
print(errorcode)
except IOError:
print("Could not read file:"), filename
def get_input(phone_number_to_dial = input("enter phone number>> ")):
try:
assert (phone_number_to_dial.startswith('+') and phone_number_to_dial[
1:].isdigit()) or phone_number_to_dial[
:].isdigit(), 'Invalid phone number'
assert len(phone_number_to_dial) > 2, 'Phone number too short'
# had this at 9 but changed it to 2 for calling 112
assert len(phone_number_to_dial) < 16, 'Phone number too long'
except Exception as e:
print(e)
exit()
else:
return (phone_number_to_dial)
if __name__ == '__main__':
operator_list = read_operator_rate_file()
get_input()
I'm not sure why exactly it happens like that, but I would imagine that the default argument is evaluated when the function is defined, which is before you call your code.
Rather than
def get_input(phone_number_to_dial = input("enter phone number>> ")):
I would suggest that you use something like:
def get_input(phone_number_to_dial=None):
if phone_number_to_dial is None:
phone_number_to_dial = input("enter phone number>> ")

I need with perfecting a project for beginners in terms of writing to a file

I'm trying to make sure the input the user uses is all letters.I tried the .alpha method but since this is a file, a "." will be included returning it false. I also tried using "quit" sentinel value to exit the program but that isn't working. It keeps saying break is outside the loop. I also want the user to keep inputting if the file is not found error is raised.
The Assignment1
def main():
fileName = inputTxt()
FiletoReadFrom = openingFile(fileName)
counter = 0
for line in FiletoReadFrom:
outputFile = open("output.txt", "a+")
counter = counter + 1
outputFile.write("/* {} */ {}\n".format(counter, line.strip()))
if counter == 0:
print("This is an empty file")
else:
print("The file has been made")
FiletoReadFrom.close()
outputFile.close()
def inputTxt():
flag = True
while flag == True:
FileName= input("Please Enter the Name of the File, or type quit to exit ")
if FileName == quit:
flag == False
break
print("goodbye")
else:
return FileName
def openingFile(filetoReadFrom):
try:
a = open(filetoReadFrom, 'r')
return a
except FileNotFoundError:
print("This File was not Found", "Enter again or type quit to exit")
main()
There are different questions here, which is frowned upon on this site. Please never do that again.
the quit and break problem:
It is just a typo. As you forgot quoting 'quit', Python sees it at an undeclared variable which gives a syntax error. Fix:
...
while flag == True:
FileName= input("Please Enter the Name of the File, or type quit to exit ")
if FileName == 'quit':
flag == False
break
...
But it is still wrong, because break will only exit from the loop and inputTxt will return None which is not what you expect. Calling sys.exit() could be better here.
Test for letters and not numbers:
You must choose a white list (only alphas and dot) or black list (no numbers) way. In idiomatic Python it could be:
if all((x.isalpha() or x == '.') for x in FileName): # white list
# process error condition
if any(x.isdigit() for x in FileName): # black list
# process error condition
You could also use the re module which is great at controlling that a string respect a given pattern...
keep asking until a valid file is given:
You should use a loop:
def main():
while True:
fileName = inputTxt()
FiletoReadFrom = openingFile(fileName)
if FileToReadFrom is not None: # openingFile returns None when file does not exist
break
But IMHO, you should remove the openingFile function and directly use (and test) open in main

How to continue loop while checking if file exists using function in python

I'm trying to create a code that will use a function to check if the file exists and if not then it will ask the user for a file name again. This loop should continue until an existing file name is given. I managed to do the same concept using a function to check if the first input was an integer but I can't seem to replicate it for the file name portion without getting an error(FileNotFoundError: [Errno 2] No such file or directory:) and ending the loop. (it still prints the "not valid file" bit but it ends in an error)
Here's a snippet from my code:
def checkInt(val):
try:
val = int(val)
return val
except:
print('Not a valid integer')
def checkFile(fileName):
try:
File = open(fileName)
File.close
except:
print('Not a valid file.')
def main():
print('Hi welcome to the file processor')
while 1:
val = checkInt(input('''Selection Menu:
0. Exit program
1. Read from a file
'''))
if val == 0:
print('goodbye')
quit()
elif val == 1:
fileName = input('Enter a file name: ')
checkFile(fileName)
inFile = open(fileName,'r')
print(inFile.read())
inFile.close
main()
I feel like its an obvious mistake and I greatly appreciate the insight!
You may add the exception FileNotFoundError: and continue within the loop:
def checkInt(val):
try:
val = int(val)
return val
except:
print('Not a valid integer')
def main():
print('Hi welcome to the file processor')
while 1:
val = checkInt(input('''Selection Menu:
0. Exit program
1. Read from a file
'''))
if val == 0:
print('goodbye')
exit()
elif val == 1:
fileName = input('Enter a file name: ')
checkInt()
inFile = open(fileName, 'r')
print(inFile.read())
inFile.close
OUTPUT:
Hi welcome to the file processor
Selection Menu:
0. Exit program
1. Read from a file
1
Enter a file name: blahblah
Not a valid file.
Selection Menu:
0. Exit program
1. Read from a file
1
Enter a file name: hey.txt
5,7,11,13,17,19,23,29,31,37,41,43,47,
Selection Menu:
0. Exit program
1. Read from a file
EDIT:
you can do the same within the checkFile method, just call your main():
def checkFile(fileName):
try:
File = open(fileName)
File.close
except FileNotFoundError:
print('Not a valid file.')
main()
import os
def checkFile():
file_name = input("Enter File name: ")
while(os.path.isfile(file_name )==False):
print("Not a valid file")
file_name = input("Enter File name: ")
return True # if the function is expecting a boolen, else return the filename to open it

Looping a Try/Except block until a file can be read

I have a try/except block in a function that asks the user to enter the name of a text file to open. If the file does not exist, I want the program to ask the user for the filename again either until it is located or the user hits ENTER.
Right now the try/except block just runs infinitely.
def getFiles(cryptSelection):
# Function Variable Definitions
inputFile = input("\nEnter the file to " + cryptSelection +\
". Press Enter alone to abort: ")
while True:
if inputFile != '':
try:
fileText = open(inputFile, "r")
fileText.close()
except IOError:
print("Error - that file does not exist. Try again.")
elif inputFile == '':
input("\nRun complete. Press the Enter key to exit.")
else:
print("\nError - Invalid option. Please select again.")
return inputFile
You need to break out of the while loop, this has to be done at 2 places:
After reading the file (when it is a correct file)
After the Enter key is pressed. because we want to end.
Also you need to prompt the question inside the loop so the question is asked again at every iteration and the inputFile value is updated with the latest user input
One last thing, I think your else clause can be removed as it is never accessed, the if and elif catch all the possibilities (ie, inputFile has a value or not).
def getFiles(cryptSelection):
while True:
inputFile = input("\nEnter the file to %s. Press Enter alone to abort:" % cryptSelection)
if inputFile != '':
try:
fileText = open(inputFile, "r")
fileText.close()
# break out of the loop as we have a correct file
break
except IOError:
print("Error - that file does not exist. Try again.")
else: # This is the Enter key pressed event
break
return inputFile
you have a while True but no break in your code you probably want to break after the fileText.close() like this:
try:
fileText = open(inputFile, "r")
fileText.close()
break
except IOError:
print("Error - that file does not exist. Try again.")
but really you should change this check to use os.path.isfile like this:
import os
def getFiles(cryptSelection):
inputFile = input("\nEnter the file to " + cryptSelection +\
". Press Enter alone to abort: ")
while True:
if inputFile != '':
if os.path.isfile(inputFile):
return inputFile
else:
print("Error - that file does not exist. Try again.")
elif inputFile == '':
input("\nRun complete. Press the Enter key to exit.")
else:
print("\nError - Invalid option. Please select again.")
That is because you don't assign a new value to inputFile within the while loop.
It will hold the same value forever...
EDIT
Once you will assign a new value to inputFile within the loop - make sure to break out when the exit condition is met ("user hits Enter")

How to break from the while loop? For Python string type

# Let's create a file and write it to disk.
filename = "test.dat"
# Let's create some data:
done = 0
namelist = []
while not done:
name = raw_input("Enter a name:")
if type(name) == type(""):
namelist.append(name)
else:
break
For the Python code above, I tried, but could not break from the while loop. It always asks me to "Enter a name:", whatever I input.
How to break from the loop?
# Let's create a file and write it to disk.
filename = "test.dat"
# Let's create some data:
namelist = []
while True:
name = raw_input("Enter a name:")
if name:
namelist.append(name)
else:
break
This breaks when entered nothing
This is because raw_input always returns a string, i.e., type(name) == type("") is always true. Try:
while True:
name = raw_input("Enter a name: ")
if not name:
break
...

Categories

Resources