[英]Should I open a file outside or inside a function?
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. 也许这个问题没有道理,但是我想知道是否存在关于如何将文件传递给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 ? 是否有理由使用一种方法代替另一种方法?
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
. 当一个函数使用一个打开的文件对象时,可以更轻松地与其他类似文件的对象一起使用,例如s
io.StringIO
。 On the other hand, using a with
statement inside a function is very elegant. 另一方面,在函数内部使用
with
语句非常优雅。 A hybrid solution would be accepting both a path (string) and a file-like object. 混合解决方案将同时接受路径(字符串)和类似文件的对象。 Several libraries do that.
几个库可以做到这一点。
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 .
这意味着将可以更轻松地将功能与其他类型的文件一起重用,而不仅仅是在磁盘上具有路径的文件,例如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. 您仍可以在对象之类的文件上使用
with
语句,不必仅在打开它时使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.