0

I am trying to write a program that asks for a specific file name and then processes the input file name to make a list out of it. The limitation is that the user has only three chances to type the correct file name. Here are my codes:

    import os.path

def file_name_tries():
    for i in range(3):
        filename = input('please enter filename: ')
    try:
        infile = open(filename,'r')
        # Do whatever you want, e.g.
        #print infile.read()
        return infile
        exit()
    except IOError:
        if not os.path.exists(filename): print ('File does not exist')
        else: print ('Error opening file')

    print ('you have exceed your three tries' )   
def process_file():
    #file_name=input('file name: ')
    #input_file=open(file_name,'r')
    input_file=file_name_tries()
    input_list=[]
    #for loop strips each line of end characters
    #and splits each line of the input file at ; and turns the line to a list
    for line in input_file:
        line_list=line.strip().split(';')
        #appends each line_list to input_list
        input_list.append(line_list)
    print( input_list)
process_file()

ERROR:

please enter filename: mlb.txt
please enter filename: mlb.txt
please enter filename: mlb.txt
File does not exist
you have exceed your three tries
Traceback (most recent call last):
  File "C:\Users\Dasinator\Documents\Books IX\Python Examples\textbook examples\project   07\passwordenter3times.py", line 29, in <module>
    open_file()
  File "C:\Users\Dasinator\Documents\Books IX\Python Examples\textbook examples\project 07\passwordenter3times.py", line 24, in open_file
    for line in input_file:
TypeError: 'NoneType' object is not iterable

I would appreciate any suggestion. Thanks

2
  • erm, why do you even need open_file()? just call file_name_tries(). I'm a little confused. Do you want to interactively checks whether file exist? or ask user to enter 3 files and check which files exist? You need to clarify the task for us to help you better. =) Commented Mar 16, 2014 at 6:36
  • It is part of a bigger program. Sorry, trying to give part of the program instead of the entire code (which is way too long). The first function is opening the file and the second one is processing the open file and creating a list. Commented Mar 16, 2014 at 6:42

3 Answers 3

1

Save this as test.py:

import os
for i in range(3):
    filename = raw_input('please enter filename: ')
    try:
        infile = open(filename,'r')
        # Do whatever you want, e.g.
        print infile.read()
        exit()
    except IOError:
        if not os.path.exists(filename): print 'File does not exist'
        else: print 'Error opening file'

print 'you have exceed your three tries'

Here's how it works on the terminal:

$ rm test.txt
$ python test.py
please enter filename: test.txt
File does not exist
please enter filename: test.txt
File does not exist
please enter filename: test.txt
File does not exist
you have exceed your three tries
$ echo "this is a foo bar" > test.txt
$ python test.py
please enter filename: test.txt
this is a foo bar
Sign up to request clarification or add additional context in comments.

4 Comments

I did some edit and ran your code and I am getting the new error message that I have posted in the main code. Please, take a look.
just throw your open_file() away and the code would work. why do you need the open_file()? file_name_tries() returns nothing thus the NoneType error in open_file(). Do you want to log the entries of the user? or do you want to do something else. you need to clarify the purpose of the open_file() for us to help you =).
I have changed the function name to process_file because it is calling open_file function and processing the opened file and creating a list. I hope it makes sense.
please see the other answer and check whether that's what you need.
0

To 'functionalize' the max three tries file opening, try:

import os

def three_tries():
    for i in range(3):
        filename = raw_input('please enter filename: ')
        try:
            infile = open(filename,'r')
            return infile
        except IOError:
            if not os.path.exists(filename): print 'File does not exist'
            else: print 'Error opening file'
    print '\nyou have exceed your three tries'
    print 'program ending... byebye...'
    exit()

print 'this is a foo bar script'
print 'i am going to ask the user for a filename'
infile = three_tries()
# Do whatever you want with the file, e.g.
print '\nreading file...'
print infile.read()

On terminal:

$ rm test.txt
$ python test.py
this is a foo bar script
i am going to ask the user for a filename
please enter filename: test.txt
File does not exist
please enter filename: test.txt
File does not exist
please enter filename: test.txt
File does not exist

you have exceed your three tries
program ending... byebye...
$ echo 'foo bar sentence, blah blah' > test.txt
$ python test.py
this is a foo bar script
i am going to ask the user for a filename
please enter filename: test.txt

reading file...
foo bar sentence, blah blah

If you don't want the program to end after exceeding three tries:

import os

def three_tries():
    for i in range(3):
        filename = raw_input('please enter filename: ')
        try:
            infile = open(filename,'r')
            return infile
        except IOError:
            if not os.path.exists(filename): print 'File does not exist'
            else: print 'Error opening file'
    print '\nyou have exceed your three tries'
    print 'continuing without reading any file...'
    return

print 'this is a foo bar script'
print 'i am going to ask the user for a filename'
infile = three_tries()

if infile:
    # Do whatever you want with the file, e.g.
    print '\nreading file...'
    print infile.read()
else:
    print 'no file read, continuing to other stuff...'

print 'now you can continues to other parts of the program...'

5 Comments

thanks. It is working. But, I was wondering if we could replace exit() with something else. In the case of a failure in three trials, I want the output window to stay open.
it all depends on how the bigger program interacts and how and where and when you want the program to end. But you've got the idea of how to limit tries in file opening, ;P. You could use return instead of exit() but then you have to check whether infile is None before proceeding other parts of your code. So all the bes!
In the edited version, it returns none and none is not iterable. So, the function that is using this function to process the open file and create a list is giving error. Thanks anyway for working on my problem. I will see how to modify it to make it work with other functions.
please enter filename: mlb.txt File does not exist please enter filename: mlb.txt File does not exist please enter filename: mlb.txt File does not exist you have exceed your three tries Traceback (most recent call last): File "C:\Users\Dasinator\Documents\Books IX\Python Examples\textbook examples\project 07\passwordenter3times.py", line 34, in <module> open_file() File "C:\Users\Dasinator\Documents\Books IX\Python Examples\textbook examples\project 07\passwordenter3times.py", line 29, in open_file for line in input_file: TypeError: 'NoneType' object is not iterable
Thanks for your help. I finally figured out how to use your code in my program and really appreciate your help.
0

Just replace your break when the user succeeds with return file_open (and remove the return at the bottom, which is causing the error).

Then your function will return None if the user failed three times.

2 Comments

I tried that and it is still not working. It is not even letting me enter a wrong file name three times.
Did you notice that your "for" loop which gives the 3 tries does not actually include the input() function call? So of course the user can only be prompted once. Be more methodical with your coding and it should work better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.