Novice
Novice

Reputation: 1161

How to exit for loop once valid file name is provided and give 3 chances for correct input

I am trying to write a for loop that will give a user 3 tries to provide the correct filename. What is the best way to do this or best practice?

for n in [1,2,3]:
    try:
        user_inp = input('Please provide the filename: ')  # Prompt user for file name
    # Need help here..
    # If the filename isn't found, python will give the following error: FileNotFoundError: [Errno 2] No such file or directory: 
    # If that happens, I need it to print the except statement and try again 
    # However, if the filename is correct or "FileIsFound" I need it to exit the loop--using ' break ' ?         
    except:
          print('Invalid file name, try again please')
    # Would be great if we could add a counter here like: print('You have', n, 'tries remaining') 
    continue

file_open = open(user_inp) # open file --load in memory 

for line in file_open:  # remove /n at the end of each line
line = line.rstrip()  # print statements add /n = newlines and text docs usually have /n in them
# this for loop will remove/strip the /n at the end of each line

read_file = file_open.read()  # reads entire file 
                              # NOTE: if you are dealing with large files, you may want to consider using a conditional statement to find what you are searching, extracting, etc instead of reading the entire file


print(read_file.upper())  # Prints file contents in upper case 

I would like to know how to do this with a try and except statement. Thank you!

Cheers.

Upvotes: 1

Views: 330

Answers (1)

Vivek Sable
Vivek Sable

Reputation: 10213

OS Module

Use isfile() method from the os module to check file present or not .

demo:

>>> import os
>>> os.path.isfile("/1.txt")
False
>>> os.path.isfile("/home/vivek/Desktop/file3.csv")
True
>>> 

Break keyword

Use break keyword to come out from the any iterator loop i.e. for, while

Demo

>>> c = 1
>>> while True:
...     if c==3:
...         print "Now break because value of c (%d) is equal to 3"%(c)
...         break
...     print "In loop c=%d"%c
...     c += 1
... 
In loop c=1
In loop c=2
Now break because value of c (3) is equal to 3
>>> 

Code to get File names from User and Validate File Name.

import os

file_path = ""
for n in [1,2,3]:
    user_inp = raw_input('Please provide the filename: ')
    if os.path.isfile(user_inp):
        file_path = user_inp
        break 
    print('Invalid file name, try again please')


if file_path:
    # Write ypur code.
    print "Processing file Name:", file_path
else:
    print "User not enters correct file name."

Output:

$ python test1.py
Please provide the filename: /home/Desktop/1.txt
Invalid file name, try again please
Please provide the filename: /home/Desktop/2.txt                
Invalid file name, try again please
Please provide the filename: /home/Desktop/3.txt            
Invalid file name, try again please
User not enters correct file name.

$ python test1.py
Please provide the filename: /home/Desktop/2.txt
Invalid file name, try again please
Please provide the filename: /home/vivek/Desktop/file3.csv
Processing file Name: /home/vivek/Desktop/file3.csv

Note:

Use raw_input() for Python 2.x

Use input() for Python 3.x

Upvotes: 1

Related Questions