python - 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? ,但是在这里我添加了文件名的完整路径,但无论如何它都不起作用
解决方案
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))
.
推荐阅读
- laravel - 如何在两个不同的路由组中使用相同的路由
- sql-server - SQL Server - MERGE : MATCHED 两次更新 - 基于同一表中第一次更新的记录的第二次更新
- python - Weasyprint/Cairo 在转换为 PDF 时会丢失 SVG 文本标签
- replication - 复制 ClickHouse 副本的最佳方法?
- powershell - Powershell:尝试将背景/前景颜色更改为文本输出(无写入主机)
- minecraft - 拿起_JAVA_OPTIONS。最大堆大小无效?
- algorithm - 我对2个二叉树之间的复杂性比较有点困惑,如果相同,下面是相同的代码
- java - 具有接口和验证器的泛型
- python - 有没有办法在 pandas 中创建代表三个数据帧的共享值的虚拟变量?
- macos - zsh 无法识别环境变量 - 没有这样的文件或目录 - Unix - MacOs