Home > database >  how to allow the user to enter a file name and prompt an error message if the file cannot be opened
how to allow the user to enter a file name and prompt an error message if the file cannot be opened

Time:01-15

how to allow the user to enter a file name and prompt an error message if the file cannot be opened in python

i have tried with normal read mode however when I try with user input it does not work

CodePudding user response:

There are a couple of ways to do this:

The first way is to use a try-except clause like this:

Code:

try:
    file_name = input("Enter file name: ")
    with open(file_name, 'r') as f:
        # Process the file
        contents = f.read()  # read the contents of the file
        print(contents)  # print the contents of the file
except FileNotFoundError:
    print("Error: File not found.")
except:
    print("Some other exception occurred")


Or you can use the path.exists function from the os package:

Code:

import os

file_name = input("Enter file name: ")
if os.path.exists(file_name):
    with open(file_name, 'r') as f:
        # Process the file
        contents = f.read()  # read the contents of the file
        print(contents)  # print the contents of the file
else:
    print("Error: File not found.")
  • Related