检查对象是否是Python中的文件

检查对象是否是Python中的文件

本文介绍了检查对象是否是Python中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是Python中的对象,表现为像一个真实的文件,例如有一个read()和一个write方法(),但有一个不同的实现。这是概念的实现。

File-like objects are objects in Python that behave like a real file, e.g. have a read() and a write method(), but have a different implementation. It is and realization of the Duck Typing concept.

被认为是一个好的做法,允许一个类似文件的对象到处都有一个文件,例如可以使用或Socket对象来代替真实文件。所以执行这样的支票是不好的:

It is considered good practice to allow a file-like object everywhere where a file is expected so that e.g. a StringIO or a Socket object can be used instead a real file. So it is bad to perform a check like this:

if not isinstance(fp, file):
   raise something

检查对象(例如方法的参数)是否为文件的最佳方式是什么 -

What is the best way to check if an object (e.g. a parameter of a method) is "file-like"?

推荐答案

除非您有特殊要求,否则在您的代码中完全没有这样的支票。

It is generally not good practice to have checks like this in your code at all unless you have special requirements.

在Python中,键入是动态的,为什么你觉得需要检查对象是否是文件,而不仅仅是使用它,就像它是一个文件,并处理导致错误?

In Python the typing is dynamic, why do you feel need to check whether the object is file like, rather than just using it as if it was a file and handling the resulting error?

您可以做的任何检查都将在运行时出现,所以做一些像如果不是hasattr(fp,'read')并且提高一些异常比调用 fp.read()更多的实用程序,并且如果方法不存在,则处理结果属性错误。

Any check you can do is going to happen at runtime anyway so doing something like if not hasattr(fp, 'read') and raising some exception provides little more utility than just calling fp.read() and handling the resulting attribute error if the method does not exist.

这篇关于检查对象是否是Python中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:07