0

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!

7
  • 1
    You mean a while loop? tutorialspoint.com/python/python_while_loop.htm Commented Aug 27, 2015 at 19:02
  • @PadraicCunningham I THINK so but I'm not even 100% sure since I'm just self-teaching. It looks right but I'm not sure exactly how to apply it into my script to do what I want. Commented Aug 27, 2015 at 19:08
  • Put the for loop in a while, do you want to pass new directories each time or just let them choose to read the file or not? Commented Aug 27, 2015 at 19:10
  • @PadraicCunningham No, it's going to be in the same directory each time. All that will change is what file the user wants to view. Commented Aug 27, 2015 at 19:11
  • Do you actually want to check subdirectories? Commented Aug 27, 2015 at 19:15

3 Answers 3

1

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()
Sign up to request clarification or add additional context in comments.

4 Comments

For the second option, it says invalid syntax for break if not fname
The first option also says invalid syntax for the last line of it.
Sorry. That's what comes from me switching between Ruby and Python and not having tested the code I posted. I've fixed the syntax errors, now.
I understand! Worked on first try this time.
0

By the way it is typed right now that will never happen.

You need to offer an "escape" option to your user or else he will submit files to his heart's content. ( You could try an escape condition like : if the user types 0 , you proceed to the next part which would print "Press Enter to continue..")

So pseudo-coding a bit it would look like:

initialize a list
store directory files in list
while input != escape character
  ask user for file name
  if file name inside list:
    print file
    print "Press Enter to Continue"
  else:
    print error
    print "Press Enter to Continue"

Hope that gives you a general idea.

3 Comments

I didn't want to create a list, I wanted to recursively go through all directories and subdirectories and print a list of all files, then have user input tell which one to open.
If you don't make a list of files how will he be able to choose one ?
My script already prints all of the files that it finds in the directory and subdirectories. From there, the user can choose which to view.
0

This is basically the same as what das-g answered but with the option of it actually asking if you want to continue, I'm fairly sure this should suit your needs:

def yorn():
while True:
    answer=raw_input('yes or no: ')
    if answer == 'no':
        more_script()
        break
    else:
        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()
def more_script():
print "were you would add the next portion"
yorn()

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.