我编写了以下代码,但我认为这很la脚:
def findfile1(wildcard):
"""Returns path of the first matched file. Using win32file.
>>> findfile1("D:\\Python26\\*.exe")
'D:\\Python26\\python.exe'
"""
return filepath
def findfile2(wildcard):
"Same as above, but using glob."
return filepath
try:
import win32file
findfile = findfile1
except ImportError:
import glob
findfile = findfile2
if __name__ == '__main__':
f = findfile('D:\\Python26\\*.exe')
这些函数是在导入所需的模块之前定义的,而总体结构对我来说似乎有点奇怪。
解决此类问题的常用方法是什么?我怎样才能使它更pythonic?
最佳答案
try:
import win32file
except ImportError:
win32file = None
import glob
if win32file:
def findfile(wildcard):
"""Returns path of the first matched file. Using win32file."""
...
return filepath
else:
def findfile(wildcard):
"""Returns path of the first matched file. Using glob."""
...
return filepath