jo13
jo13

Reputation: 209

How can you use a while loop so the user can open a new text file? Python

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.

Upvotes: 0

Views: 53

Answers (1)

Onilol
Onilol

Reputation: 1339

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

Upvotes: 1

Related Questions