What is wrong with this except statement? Python 3.4.3 - python

Code works until I try to handle the ValueError with an except statement. Returns an invalid syntax traceback.
def write():
filename = input('Please Enter the File name:') + '.txt';
with open (filename, "a") as f:
while True:
a,b = input('Enter in format Name,Carbs per 10 grams').split(',')
a = str (a)
b1 = float (b)
f.write (a+','+ b+ '\n');
except ValueError:
continue
loop = input ('Do you want to add anything else y/n:')
if loop == 'n':
break

I don't see a try statement in your code. You probably want something like this. See the docs for more examples.
while True:
try:
a,b = input('Enter in format Name,Carbs per 10 grams').split(',')
a = str (a)
b1 = float (b)
f.write (a+','+ b+ '\n');
except ValueError:
continue

You need to have a try statement to have an except statement.
def write():
filename = input('Please Enter the File name:') + '.txt';
with open (filename, "a") as f:
while True:
try: #added try statement
a,b = input('Enter in format Name,Carbs per 10 grams').split(',')
a = str (a)
b1 = float (b)
f.write (a+','+ b+ '\n');
except ValueError:
continue
loop = input ('Do you want to add anything else y/n:')
if loop == 'n':
break

Related

In Python, How can I create a while loop using input + 'filename'

I am wanting to create a loop for my book reader so that when the user inputs a number other than 1-10, an error message comes up, and when they press 0 the program quits. However, an error message appears saying FileNotFoundError: No such file or directory: '11.txt'(etc)
import time
option = str(input('Which Book would you like to read? (1-10): '))
while option !=0:
number_of_words = 0
f=open(option + '.txt', encoding='utf-8')
file_contents=f.read()
lines = file_contents.split()
number_of_words += len(lines)
print('Word Count:',number_of_words)
time.sleep(2)
f=open(option + '.txt', encoding='utf-8')
for line in f:
print(line)
time.sleep(0)
else:
print("404 file not found")
print()
option=str(input('Which Book would you like to read?(1-10):'))
print("Goodbye")
Try this:
import time
while True:
try: # Wrap the input in a try except and try to convert it directly to an integer.
option=int(input('Which Book would you like to read? (1-10): '))
except:
print("Please only enter a number.")
continue
if option == 0:
print("Goodbye")
break
if option > 10:
print("Invalid book entered, try again, must be between 1 and 10.")
continue
with open(str(option) + '.txt', encoding='utf-8') as f: # Use a context manager to open files, it will make sure your files are closed after opening
file_contents=f.read()
number_of_words = len(file_contents.split())
print('Word Count:',number_of_words)
time.sleep(2)
for line in file_contents:
print(line)
Results:
Which Book would you like to read? (1-10): few
Please only enter a number.
Which Book would you like to read? (1-10): 121
Invalid book entered, try again, must be between 1 and 10.
Which Book would you like to read? (1-10): 0
Goodbye

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

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

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

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

Menu prompt doesn't work

I have written an application in Python to work with strings, i made a menu prompt from which i can select an operation to do, i tested all the functions, they work well, except the menu and main functions, that when i enter my choice nothing happens. Here's the code:
import re
import os
def searchInFile(searched, file):
try:
f = open(file)
except IOError.strerror as e:
print("Couldn't open the file: ", e)
else:
sea = re.compile(searched, re.IGNORECASE)
for line in f:
if re.search(sea, line):
print(line, end='')
def validateWithPattern(string):
patt = re.compile('([a-z0-9-_.])+#([a-z]+.)([a-z]{2,3})', re.IGNORECASE)
if re.search(patt, string):
print("Valid")
else:
print("Not valid!")
def menu():
print("|================MENU=================|\n", end='')
print("|0- Exit the program |\n", end='')
print("|1- Validate mail address |\n", end='')
print("|2- Search a string in a file |\n", end='')
print("|=====================================|\n", end='')
b = input("->")
return b
def main():
b = 10
while b != 0:
b = menu()
if b == 1:
a = input('Enter you mail address: ')
validateWithPattern(a)
elif b == 2:
a = input('Enter the file name: ')
c = input('Enter the string: ')
searchInFile(c, a)
elif b == 0:
os.system("PAUSE")
else: print("Choice error")
if __name__ == "__main__":
main()
Your b variable you are returning from menu function is a string, not an integer, so you can't compare it with numbers (input is automatically saved as string). If you use return int(b) instead of return b, it will be ok.
Also, I think your else: print("Choice error") should be indented the same way your if and elif are, since you probably want to write "Choice error" only if b is not one of given choices. The way it is indented in your code will print "Choice error" after the while loop ends and it will not print that message if you input the value it can't recognize (for example 3).

Categories

Resources