简体   繁体   English

我应该在函数外部还是内部打开文件?

[英]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.

相关问题 我应该在main()内部还是外部定义函数? - Should I define functions inside or outside of main()? 我应该在单元测试文件中包含要测试的功能,还是应该将其导入单元测试文件中? - Should I include the function that I am testing inside the unittest file, or should I just import it in the unittest file? 无法打开我在 function 中创建的 json 文件 - Cannot open a json file I am creating inside a function 我应该在while循环内还是外部提交到数据库? - Should I commit to my database inside the while loop or outside? 我该如何调用main函数之外定义的函数? - How should I call functions defined outside of the main function? 如何使用在函数内部,函数外部定义的变量? - How do i use a variable that is defined inside of a function, outside of a function? 在函数内部或外部循环? - Loop inside or outside a function? 我在 function 内声明了一个全局变量,但在 function 之外它是“未定义的”,它还在 function 内说它是未定义的 - I declare a global variable inside a function, but outside the function it is "undefined", it also says inside the function that it is undefined 我应该使用`with open(file):`if if`pd.read_csv`? - Should I use `with open(file):` if I `pd.read_csv`? 在写入或全局写入的函数内打开与Redis数据库的连接是一种好的做法吗? - Is it a good practice to open connection to Redis database inside the function that writes to it or outside globally?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM