Search code examples
pythonpython-2.7loopsraw-input

How to accept user input multiple times and then execute the rest of the script when they're done?


I want to write a script where a user can get a list of all of the files in a directory and then type in the full filename to view them. Right now, my script will let a user do this once and then it continues onto the next portion of the script. I would like it to stay at this part and have them be able to keep typing in filenames and going through as many files as they want to. And then, I want it to say something like "Press Enter to continue..." and then it will continue to the next part of the script. I think it's going to be some kind of loop but I'm very new to Python. I hope that all makes sense.

Here's what I have so far.

for root, dirs., files in os.walk("/home/user/Documents"):
    for file in files:
        print(os.path.join(root, file))
fname = raw_input('Enter filename to view:')
f = open(fname, 'r')
print f.read()

So I want it to repeat with the user typing in another filename each time, and when the user chooses to do so, they can continue onto the next portion of my script. Right now it only goes through once before going on. Thanks in advance for your help!


Solution

  • As Padraic indicates in his comment, a while statement is probably the best match for this program flow. Maybe like this:

    import os
    
    def does_user_want_to_continue():
        # implement this, so it returns True or False,
        # depending on what your user wants.
        # Probably involves asking the user and accepting their input.
    
    should_continue = True
    while should_continue:
        for root, dirs, files in os.walk("/home/user/Documents"):
            for file in files:
                print(os.path.join(root, file))
        fname = raw_input('Enter filename to view:')
        f = open(fname, 'r')
        print f.read()
        should_continue = does_user_want_to_continue()
    

    You can also break out of the loop from inside it, instead of by changing what its condition-expression evaluates to:

    import os
    
    while True:
        for root, dirs, files in os.walk("/home/user/Documents"):
            for file in files:
                print(os.path.join(root, file))
        fname = raw_input('Enter filename to view '
                          '(leave empty to proceed without viewing another file):')
    
        if not fname:  # Empty strings are 'falsy'.
            break
    
        # The rest of the while clause will only be executed
        # if above we didn't break out of the loop. If we did
        # break out, the script continues with the code after
        # this loop.
        f = open(fname, 'r')
        print f.read()