首页 > 解决方案 > os.path.isfile() 返回 False

问题描述

为什么这段代码什么都不返回?

>>> [f for f in os.listdir('Scripts') if os.path.isfile(os.path.abspath(f))]
[]
>>> os.listdir('Scripts')
['dmypy.exe', 'easy_install-3.8.exe', 'easy_install.exe', 'f2py.exe', 'futurize.exe', 'iptest.exe', 'iptest3.exe', 'ipython.exe', 'ipython3.exe', 'mypy.exe', 'mypyc', 'pasteurize.exe', 'pip.exe', 'pip3.8.exe', 'pip3.exe', 'prichunkpng', 'priforgepng', 'prigreypng', 'pripalpng', 'pripamtopng', 'pripnglsch', 'pripngtopam', 'priweavepng', 'pygmentize.exe', 'pyi-archive_viewer.exe', 'pyi-bindepend.exe', 'pyi-grab_version.exe', 'pyi-makespec.exe', 'pyi-set_version.exe', 'pyinstaller.exe', 'stubgen.exe', 'stubtest.exe', 'wheel.exe']

我明白这个问题的答案Why do os.path.isfile return False? ,但是在这里我添加了文件名的完整路径,但无论如何它都不起作用

标签: pythonpython-os

解决方案


abspath这不是正确的工具。os.join与“脚本”目录一起使用:

[f for f in os.listdir('Scripts') if os.path.isfile(os.path.join("Scripts", f))]

关于abspath- 根据文档,它基本上将当前工作目录连接到文件名。如果您正在查看的文件不在当前目录中,这不是您想要的。

引用文档:

abspath: ... 在大多数平台上,这相当于调用函数normpath()如下:normpath(join(os.getcwd(), path)).


推荐阅读