0

I am writing a function that helps in opening a user-supplied file. Here is what I have so far:

def main():

    open_file()


def open_file():
    input_file_name = str(input("Input file name: "))
    while input_file_name != 'measles.txt':
        input_file_name = str(input("Please enter a valid input file name: "))
    f1 = open(input_file_name, 'r')
    return f1

main()

My question is: once I call open_file in main, how do I close the file that I opened in the open_file function?

3 Answers 3

3

One way is to use the with statement:

def main():
    with open_file() as f:
        # use f here

The file will automatically be closed when the code exists from the with statement.

0

As you return the file object from open_file(), you can (have to) pick it up somehow. YOu do so by using the function call as (a part of) an expression.

So either do

f = open_file()

and do whatever you need, or do

open_file().close()

being a shorthand of

f = open_file()
f.close()

(both of them being quite pointless)

or, which seems the most appropriate thing to do,

with open_file() as f:
    do_whatever(f)

being a shorthand of

f = open_file()
with f:
    do_whatever(f)

which closes the file automatically.

0
0

You can also create a variable that references the file object, and use that to close the file manually later on:

def main():
    f = open_file()
    # Operate on file ...
    f.close()