1

This is my basic code:

fname = input("What is the name of the file to be opened")
    file = open(fname+".txt", "r")
    message = str(file.read())
    file.close()

What I want to do is essentially make sure the file the program is attempting to open exists and I was wondering if it was possible to write code that tries to open the file and when it discovers the file doesn't exist tells the user to enter a valid file name rather then terminating the program showing an error.

I was thinking whether there was something that checked if the code returned an error and if it did maybe made an variable equal to invalid which an if statement then reads telling the user the issue before asking the user to enter another file name.

Pseudocode:

fname = input("What is the name of the file to be opened")
        file = open(fname+".txt", "r")
        message = str(file.read())
        file.close()
if fname returns an error:
    Valid = invalid
while valid == invalid:
    print("Please enter a valid file name")
    fname = input("What is the name of the file to be opened")

if fname returns an error:
    Valid = invalid

etc.

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Aslinnl
  • 47
  • 1
  • 7
  • 1
    You should read about exception handlers (`try` / `except` / `finaly` blocks) or you may also use functions like [`os.path.isfile`](https://docs.python.org/2/library/os.path.html#os.path.isfile) – awesoon Oct 29 '15 at 05:27
  • Check this SO post. http://stackoverflow.com/questions/82831/check-whether-a-file-exists-using-python – WGS Oct 29 '15 at 05:28

2 Answers2

1

I guess the idea is that you want to loop through until your user enters a valid file name. Try this:

import os

def get_file_name():
    fname = input('Please enter a file name: ')
    if not os.path.isfile(fname+".txt"):
      print('Sorry ', fname, '.txt is not a valid filename')
      get_file_name()
    else:
      return fname

file_name = get_file_name()
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
1

Going by the rule Asking for forgiveness is better then permission

And using context-manager and while loop

Code :

while True: #Creates an infinite loop
    try:
        fname = input("What is the name of the file to be opened")
        with open(fname+".txt", "r") as file_in:
            message = str(file_in.read())
        break #This will exist the infinite loop
    except (OSError, IOError) as e:
        print "{} not_available Try Again ".format(fname)
Community
  • 1
  • 1
The6thSense
  • 8,103
  • 8
  • 31
  • 65