Question

This works as expected BUT when I enter a input that is incorrect more than one...

This works as expected BUT when I enter a input that is incorrect more than one time, the second time it stops works.

It works as expected and redisplays the prompt after the first time an exception is raised but crashes the second. Any help appreciated!

-------------------------------------------------------------------------

# This program will open and read a list of numbers in a text file and then terminate

def nums():
  
prompt = input("Please enter the name of your file: ")
  
  read_numbers = prompt
# This is the variable that keeps track of the text file

numbersInput = open(read_numbers, 'r')
# References the variable 'read_numbers' to open the text file

numString = numbersInput.read()
# references the variable 'numbersInput' and reads the text file

print(numString)
# Prints the contents of the text file to the shell

numbersInput.close()
# Closes the text file

def main():
try:
nums()
except FileNotFoundError:
print("This file is not available!",'\n')
nums()
except:
print("There has been an error!",'\n')
nums()

main()

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The answer to this question is as follows:

The code is as follows:

def nums():
prompt = input("Please enter the name of your file: ")
read_numbers = prompt
numbersInput = open(read_numbers, 'r')
numString = numbersInput.read()
print(numString)
numbersInput.close()
def main():
while True:
try:
nums()
except FileNotFoundError:
print("This file is not available!",'\n')
except:
print("There has been an error!",'\n')
nums()

main()

The input and output are provided in the screenshot below:

Add a comment
Know the answer?
Add Answer to:
This works as expected BUT when I enter a input that is incorrect more than one...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Need to check if File is successfully opened? C++ It works when I input the right...

    Need to check if File is successfully opened? C++ It works when I input the right txt file. But, it keeps stating, File successfully open." even I put in a non-existing file. Here are the specifications: Develop a functional flowchart and then write a C++ program to solve the following problem. Create a text file named first.txt and write your first name in the file. You will be reading the name of the file from the keyboard as a string,...

  • Write a class called TemperatureFile. • The class has one data attribute: __filename • Write get...

    Write a class called TemperatureFile. • The class has one data attribute: __filename • Write getter and setter for the data attribute. • Write a “calculateAverage” function (signature below) to calculate and return average temperature of all temperatures in the file. def calculateAverage(self): • Handle possible exceptions Write a main function: • Create a file ('Temperatures.txt’) and then use “write” method to write temperature values on each line. • Create an object of the TemperaureFile with the filename (‘Temperatures.txt’) just...

  • Problem 1 Recall that when the built-in function open() is called to open a file for...

    Problem 1 Recall that when the built-in function open() is called to open a file for reading, but it doesn't exist, an exception is raised. However, if the file exists, a reference to the opened file object is returned. Write a function safeOpen() that takes one parameter, filename - a string giving the pathname of the file to be opened for reading. When safeOpen() is used to open a file, a reference to the opened file object should be returned...

  • 40pts) Given the following code segment. mSwer= input("Enter age: ") ile answer != 'q' : try:...

    40pts) Given the following code segment. mSwer= input("Enter age: ") ile answer != 'q' : try: print(int(answer) ) answer input ( " Enter age: ") except Value E rror : print ("Invalid answer 'q' age") Show what is printed if the user enters the following values at the prompt, one at a time. Print output User input 20 17 2a => 29 q 9. The following main function works with a class called Student that you will write. def main()...

  • I need help in Python. This is a two step problem So I have the code...

    I need help in Python. This is a two step problem So I have the code down, but I am missing some requirements that I am stuck on. Also, I need help verifying the problem is correct.:) 7. Random Number File Writer Write a program that writes a series of random numbers to a file. Each random number should be in the range of 1 through 500. The application should let the user specify how many random numbers the file...

  • I'm a bit confused on how to get this program to run right. Here are the...

    I'm a bit confused on how to get this program to run right. Here are the directions: Part 1: Write a Python function called reduceWhitespace that is given a string line and returns the line with all extra whitespace characters between the words removed. For example, ‘This line has extra space characters ‘  ‘This line has extra space characters’ Function name: reduceWhitespace Number of parameters: one string line Return value: one string line The main file should handle the...

  • Using python 3.6 How do I incorporate 0 or negative input to raise an error and...

    Using python 3.6 How do I incorporate 0 or negative input to raise an error and let the user try again? like <=0 #loop to check valid input option. while True: try: choice = int(input('Enter choice: ')) if choice>len(header): print("Invalid choice!! Please try again and select value either:",end=" ") for i in range(1,len(header)+1): print(i,end=",") else: break choice = int(input('\nEnter choice: ')) except ValueError as ve:print('Invalid response, You need to select the number choice from the option menu') # Catch your...

  • Overview These exercises will allow you to have some practice with basic Java file Input/Output. In...

    Overview These exercises will allow you to have some practice with basic Java file Input/Output. In addition, you will also have an opportunity to have more practice with methods and arrays.   Objectives Practice with programming fundamentals Variables - Declaration and Assignment Primitive types Arithmetic Expressions Simple keyboard input and text display output Branching - if-elseif-else syntax Loops - simple while loops, nested while loops Methods - functions and procedures ArrayLists - collections of variables File I/O Works towards the following...

  • C++ please! (1) Prompt the user to enter the name of the input file. The file...

    C++ please! (1) Prompt the user to enter the name of the input file. The file will contain a text on a single line. Store the text in a string. Output the string. Ex: Enter file name: input1.txt File content: We'll continue our quest in space. There will be more shuttle flights and more shuttle crews and, yes, more volunteers, more civilians, more teachers in space. Nothing ends here; our hopes and our journeys continue! (2) Implement a PrintMenu() function,...

  • Hello I need help with python programming here is my code # Trivia Challenge # Trivia...

    Hello I need help with python programming here is my code # Trivia Challenge # Trivia game that reads a plain text file import sys def open_file(file_name, mode): """Open a file.""" try: the_file = open(file_name, mode) except IOError as e: print("Unable to open the file", file_name, "Ending program.\n", e) input("\n\nPress the enter key to exit.") sys.exit() else: return the_file def next_line(the_file): """Return next line from the trivia file, formatted.""" line = the_file.readline() line = line.replace("/", "\n") return line def next_block(the_file):...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT