曾经在Python(2.6)中可以问:
isinstance(f, file)
Run Code Online (Sandbox Code Playgroud)
但是在Python 3.0中file被删除了.
现在检查变量是否为文件的正确方法是什么?What'sNew文档没有提到这个......
def read_a_file(f)
try:
contents = f.read()
except AttributeError:
# f is not a file
Run Code Online (Sandbox Code Playgroud)
替换您计划使用的任何方法read.如果您希望在超过98%的时间内传递像对象这样的文件,那么这是最佳选择.如果您希望在超过2%的时间内传递非对象文件,那么正确的做法是:
def read_a_file(f):
if hasattr(f, 'read'):
contents = f.read()
else:
# f is not a file
Run Code Online (Sandbox Code Playgroud)
这正是你,你会怎样做可以使用一个file类来测试对抗.(还有FWIW,我也有file2.6)请注意,此代码也适用于3.x.
| 归档时间: |
|
| 查看次数: |
4552 次 |
| 最近记录: |