Reputation: 1841
Maybe this question makes no sense, but I was wondering if there was a "recommended practice" on how to pass a file to a function in Python.
Should I pass the file's path or the opened file itself ?
Should I do :
def func(file):
file.write(...)
with open(file_path, 'w') as file:
func(file)
...or :
def func(file_path):
with open(file_path, 'w') as file:
file.write(...)
func(file_path)
?
Is there some reason to use one method instead of the other ?
Upvotes: 4
Views: 7728
Reputation: 85512
Both ways have their advantages and disadvantaged. When a function takes an open file object, it becomes easier to use with other file-like object such s io.StringIO
. On the other hand, using a with
statement inside a function is very elegant. A hybrid solution would be accepting both a path (string) and a file-like object. Several libraries do that.
Upvotes: 2
Reputation: 106
Passing a file like object is recommended over passing a path. This means it will be easier to reuse your function with other types of files not just ones with a path on disk, such as BytesIO https://docs.python.org/3/library/io.html#io.BytesIO.
You can still use the with
statement on the file like object, you don't have to use it only when you open it.
Upvotes: 1