-1

So the file is called 'data.txt'. I need to write a program that prompts the user for input to see if it matches 'data.txt'. So for example, if i enter 'data', it will output:

Enter name of file:
data
File data not found.

so far, when i input 'data', my code:

# Define your functions here
if __name__ == '__main__':
    file_name = "data.txt"

    # Prompt the user for the name of the file and try opening it for reading
    user_input = ''

    while user_input in ['data.txt']:
        try:
            user_input = input('Enter name of file:')
            my_file = open('data.txt')
            lines = my_file.read()

        # Use try-except to catch an error if the file does not exist
        except:
            print('File data not found.')
        # Complete main section of code to read the file, compute the average weight and height, etc.

However, this displays (Your program produced no output).

Any tips on how to debug my code? Or what I need to fix?

yeobub
  • 55
  • 1
  • 7
  • You can try filecmp https://stackoverflow.com/a/1072576/3523510 Like write the content in file and then compare or see how it works behind the scene – Shashank May 26 '20 at 23:54
  • add a print statement in try,i think there is nothing you are printing in try block – Zesty Dragon May 26 '20 at 23:55
  • 1
    initially `user_input = ''` not in `['data.txt']` so your code never runned while loop and exit – sahasrara62 May 27 '20 at 00:18
  • I don't know if you specifically need to use try-except, but this may be worth a read: [How do I check whether a file exists without exceptions?](https://stackoverflow.com/q/82831/2745495). – Gino Mempin May 27 '20 at 00:48

3 Answers3

1

Instead of trying to open the file (and using a broad exception clause), you can check whether it exists with os.path.

import os

def ask_file():
    while True:
        file = input("What is the file?")
        if os.path.exists(file):
             return file
        print("That file does not exist!")


ask_file()
Robert Kearns
  • 1,631
  • 1
  • 8
  • 15
  • thanks, though my assignment was specifically looking for a try-except clause. will note your suggestion though! – yeobub May 27 '20 at 03:38
0

Your while loop was never executed because the condition is always false. You could try the following:

if __name__ == '__main__':
    try:
        user_input = input('Enter name of file: ')
        my_file = open(user_input)
        lines = my_file.read()

    except:
        print('File data not found.')
siralexsir88
  • 418
  • 1
  • 4
  • 14
0

Here:

try:
    f = open('text.txt')
    f.close()
except:
    print('File not found.')
Red
  • 26,798
  • 7
  • 36
  • 58