0

I want to use a while loop that will give the user an opportunity to open a new text file at the end of the program. Here is the code I have:

run_again = "yes"
run_again = run_again.upper().strip()
while run_again == "yes":
    open_file = input("Please enter name of file: ")
    file_name = open(open_file,"r")
    for line in file_name:
        line = line.strip()
        rows = line.split(" ")
        num = rows[0]
        print(num)
    run_again = input("Would you like to open a new file (yes or no)? ")
    if run_again != "yes":
        print("Have a great day!")

I've managed to make a while loop work with other code but I can't get it to work with opening text files.

4
  • 1
    What's wrong with your code exactly? Commented Sep 22, 2015 at 20:40
  • 7
    run_again = run_again.upper().strip() makes run_again equal to YES. Then you do while run_again == "yes": which is false right off the bat. Commented Sep 22, 2015 at 20:41
  • Some things I'd change: You should put the .upper().strip() lines inside the loop. You don't need the if statement in the loop (you are already testing with the while). You should close the file when you are done reading from it. Commented Sep 22, 2015 at 20:43
  • You could change run_again to True .. would be a lot cleaner Commented Sep 22, 2015 at 21:04

1 Answer 1

1

I think something like that would work. Can't really test now.

 run_again = True
    while run_again:
        open_file = input("Please enter name of file: ")
        file_name = open(open_file,"r")
        for line in file_name:
            line = line.strip()
            rows = line.split(" ")
            num = rows[0]
            print(num)

        if input("Would you like to open a new file (yes or no)? ") != "yes":
            print("Have a great day!")
            break

Edit :

As suggested by Blorgbeard :

    while True:
        open_file = input("Please enter name of file: ")
        file_name = open(open_file,"r")
        for line in file_name:
            line = line.strip()
            rows = line.split(" ")
            num = rows[0]
            print(num)

        if input("Would you like to open a new file (yes or no)? ") != "yes":
            print("Have a great day!")
            break
Sign up to request clarification or add additional context in comments.

1 Comment

while run_again: may as well be while True: and you can remove run_again, since you never access it again.

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.