【发布时间】:2018-06-05 23:42:03
【问题描述】:
我使用 Try Catch Else finally 块来创建这个函数。
这是我的代码:
def read_a_file():
"""
>>> out = read_a_file() #while the file is not there
The file is not there.
We did something.
>>> print(out)
None
>>> Path('myfile.txt').touch()
>>> out = read_a_file() #while the file is there
The file is there!
We did something.
>>> type(out)
<class '_io.TextIOWrapper'>
>>> out.close()
>>> os.remove("myfile.txt")
"""
try:
file_handle = open('myfile.txt', 'r')
return file_handle
except FileNotFoundError:
print('The file is not there.')
return None
else:
print('The file is there!')
finally:
print('We did something.')
但是,当我运行 doctest 时,打印语句永远不会在 except 和 else 块中工作。只有 finally 块中的 print 语句有效。
我得到了这个结果,这不是我想要的。
>>> out = read_a_file() #while the file is not there
We did something.
帮助!!!如何解决这个问题?
你必须导入这些包
import pandas as pd
from functools import reduce
from pathlib import Path
import os
【问题讨论】:
-
我无法使用 Python 3.6.3 重现此问题
-
在我看来文件在在那里,可能是因为之前的 doctest 在删除文件之前失败了。
-
我在 python 3.6.0 上运行了你的代码,它按预期工作
标签: python python-3.x