Reputation:
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?
Upvotes: 0
Views: 1459
Reputation: 91017
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.
Upvotes: 0
Reputation: 5280
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()
Upvotes: 0
Reputation: 500177
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.
Upvotes: 3