EatMyApples
EatMyApples

Reputation: 475

Checking if .txt file is loaded

My program has got a menu with different options. if you select l or L it will load the packages.txt file. That works fine.

    if option.upper() == 'L':
        f = open( "packages.txt", "r" )

Then if you select d or D (d for display) it should check if the file is loaded and then display("print") the information given in the file.

if option.upper() == 'D':
    if open( "packages.txt", "r" ):
        a = []
        for line in f:
            a.append(line)
            print(line)

    if open( "packages.txt", "r" ):
        print("fail")

That is the code i wrote, the printing and displaying works fine, but I cant get my head around the if file open statement.

Upvotes: 0

Views: 192

Answers (1)

Gareth Latty
Gareth Latty

Reputation: 89017

The issue here is you are opening the file again, rather than checking the existing file:

f = None

...

if option.upper() == 'L':
    f = open( "packages.txt", "r" )
elif opetion.upper() == 'D':
    if f and not f.closed:
        ...
    else:
        print("File not opened.")

Note that this is generally a bad idea. It's a much better idea to only open the file when you need it.

So, the better option is something like this:

selected = option.upper()
filename = None

if selected == "L":
    filename = "packages.txt"
elif selected = "D":
    if filename:
        with open(filename, "r") as f:
            ...
    else:
        print("The file to display has not been selected.")

Note my use of the with statement, which is more readable and ensures the file is closed properly, even if you have an exception.

Upvotes: 3

Related Questions