Click here to Skip to main content
15,949,741 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do I make sure that the program asks the user for input again, when the user enters a file that already exists or doesnt exist? depending on the function that the user has called like for example if the user wants to delete a file if he enters a file name that doesnt exist the program prompts an error and ask for the input again instead of showing "
FileNotFoundError: [WinError 2] The system cannot find the file specified
FileNotFoundError: [WinError 2] The system cannot find the file specified
, also i want the code to be short so that i have to make small adjustments
Here's is the code
<pre>def read(filename):
    while True:
        try:
            filename = str(input("Enter the file name: "))
            with open(filename, 'r') as f:
                for content in f.readlines():
                    print(content)
            break
        except FileNotFoundError:
            print("Doesn't exist! ")
            continue


####### read function ##########
def first_n_lines_from_a_file(filename, line_to_read):  #### to read from last just put -line_to_read
    with open(filename, 'r') as f:
        for line in (f.readlines()[line_to_read:]):
            print(line, end="")


######## First n lines ############
def append_to_file(filename, write_to_file):
    with open(filename, 'a') as f:
        f.write(write_to_file)


######## Append ########
def string_to_search_and_line_number(filename, string_to_search):
    line_number = 0
    list_of_results = []
    # Open the file in read only mode
    with open(filename, 'r') as read_obj:
        # Read all lines in the file one by one
        for line in read_obj:
            # For each line, check if line contains the string
            line_number += 1
            if string_to_search in line:
                # If yes, then add the line number & line as a tuple in the list
                list_of_results.append((line_number, line.rstrip()))
        # Return list of tuples containing line numbers and lines where string is found
    print(list_of_results)


def del_file(filename):
    import os
    os.remove(filename)


def new_file(filename):
    with open(filename, "x") as file:
        pass


def replace_text(filename, text_to_search):
    import fileinput
    import os
    import sys
    with open(filename, 'r+') as file:
        text_to_replace = str(input("Enter the word to replace with: "))
        count = 0
        for line in fileinput.input(filename):
            if text_to_search in line:
                count += 1
                print("Match found!", "\n", "Line Number: ", count)
            elif text_to_search not in line:
                print("Match not found!")
                count += 1
            file.write(line.replace(text_to_search, text_to_replace))


################### main program #############################
print("Type 0 to quit!", "\n", "Type 1 to read the file", "\n", "Type 2 to read first n lines of a file", "\n",
      "Type 3 to append to the file", "\n", "Type 4 to Search a string along with the line number in the file", "\n",
      "Type 5 to create a new file", "\n", "Type 6 to delete a file", "\n",
      "Type 7 to replace text in a file")  ### menu prompt ####
while True:  ## to re-run the program based on user input ###
    while True:
        try:
            user_input = int(input("Input: "))
            break
        except:
            print("invalid response! ")
    while user_input > 7 or user_input < 0:  #### so that it is in range ####
        print("Invalid response!")
        user_input = int(input("Input: "))
    if user_input == 1:
        read("")
    elif user_input == 2:
        filename = input("Enter the file name: ")
        line_to_read = int(input("Enter the line to read: "))
        first_n_lines_from_a_file(filename, line_to_read)
    elif user_input == 3:
        filename = input("Enter the file name: ")
        write_to_file = str(input("Enter the word you want to append: "))
        append_to_file(filename, write_to_file)
    elif user_input == 4:
        filename = input("Enter the file name: ")
        string_to_search = str(input("Enter the string you want to search: "))
        string_to_search_and_line_number(filename, string_to_search)
    elif user_input == 6:
        filename = input("Enter the file name: ")
        del_file(filename)
    elif user_input == 5:
        filename = input("Enter the file name: ")
        new_file(filename)
    elif user_input == 7:
        filename = input("Enter the file name: ")
        text_to_search = input("Enter the word you want to search: ")
        replace_text(filename, text_to_search)
    elif user_input == 0:
        print("Quiting....")
        quit()
    ##### to re--run the program ######
    while True:
        answer = str(input('Run again? (y/n): '))
        if answer in ('y', 'n'):
            break
        else:
            print("invalid input! ")
    if answer == 'y':
        continue
    else:
        print("Goodbye")
        break

This is the Output when i enter a file name that doesnt exist
---------OUPTPUT---------------------
Type 0 to quit! 
 Type 1 to read the file 
 Type 2 to read first n lines of a file 
 Type 3 to append to the file 
 Type 4 to Search a string along with the line number in the file 
 Type 5 to create a new file 
 Type 6 to delete a file 
 Type 7 to replace text in a file
Input: 6
Enter the file name: wwe
Traceback (most recent call last):
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'wwe'


What I have tried:

I have tried try/except by putting the File Not found error but it for some reason is not doing what it's suppose
Posted
Updated 9-Jul-22 6:23am

1 solution

Look at your code:
Python
elif user_input == 6:
    filename = input("Enter the file name: ")
    del_file(filename)

But the del_file code is not inside a try/catch block so if the file does not exist you get a system exception. You should create a function that gets the filename and checks if it exists first. You should also add a count so the user does not spend the rest of their life typing invalid names.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900