我第一次遇到这个问题,它是偶然而有趣的。
如果路径末尾有空格,则os.path.exists不会确定错误的路径。 ( Windows )
os.path.exists('C:\Python37 ') # true
或者这是另一个示例:
def get_files_from_folder(path):
try:
if os.path.isdir(path) and os.path.exists(path):
return os.listdir(path)
else:
return []
except FileNotFoundError:
return "Error: the path doesn't exist"
print(get_files_from_folder('C:\Python37'))
# ['DLLs', 'Doc' ...]
print(get_files_from_folder('C:\Python37 '))
# Error: the path doesn't exist
在第二种情况下,该函数应该返回一个空列表是合乎逻辑的,因为在if状态下,第二种条件为false……但这不会发生。
怎么了?为什么会这样?
我只有一种方法可以验证这种情况。
try:
if os.path.isdir(path) and os.path.exists(path) \
and type(os.listdir(path)) is list:
...
except FileNotFoundError:
...
但这太丑了。
p.s。 python 3.7
编辑: @MrFuppes正确指出,空格不能位于文件夹名称的末尾
可能的解决方案:
import platform
if platform.system() == "Windows":
path=path.rstrip()
比类型比较好一点。