python - os.path.isfile() 不起作用。为什么?

标签 python listdir

我正在尝试这样做:

import os
[x for x in os.listdir('.') if os.path.isfile(x)]
[x for x in os.listdir('dirname') if os.path.isfile(x)]
[x for x in os.listdir(os.path.abspath('dirname')) if os.path.isfile(os.path.abspath(x))] 

第一行有效:

[x for x in os.listdir('.') if os.path.isfile(x)]

但接下来的两个:

[x for x in os.listdir('dirname') if os.path.isfile(x)]

[x for x in os.listdir(os.path.abspath('dirname')) if os.path.isfile(os.path.abspath(x))] 

只输出[]

为什么?

最佳答案

因为需要加入dirnamexos.listdir()直接列出内容,内容没有完整路径。

例子-

[x for x in os.listdir('dirname') if os.path.isfile(os.path.join('dirname',x))]

当没有给出完整路径时,os.path.isfile() 在当前目录中搜索,因此当您将 '.'os .listdir() 你会得到一个正确的列表。


例子-

假设某个文件夹 - /a/b/c - 包含文件 - xy

当你执行 - os.listdir('/a/b/c') 时,返回的列表看起来像 -

['x','y']

即使您在 os.listdir() 中给出绝对路径,列表中返回的文件也将具有该目录的相对路径。您需要手动加入 dir 和 x 以获得正确的结果。


在您的第三个示例中,它不起作用,因为 os.path.abspath() 也适用于当前目录,因此如果您执行类似 -

os.path.abspath('somefile')

产生的结果将是 - /path/to/current/directory/somefile - 它不会验证那是否是一个真实的文件/目录。

documentation中明确说明(强调我的)-

os.path.abspath(path)

Return a normalized absolutized version of the pathname path. On most platforms, this is equivalent to calling the function normpath() as follows: normpath(join(os.getcwd(), path)).

其中 os.getcwd() 返回当前工作目录的路径。

关于python - os.path.isfile() 不起作用。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32157127/

相关文章:

python - pip 无法工作,即使它已正确安装

Python PermissionError : [WinError 32] The process cannot access the file. ....但我的文件已关闭

python - 检查 mp3 文件是否在给定目录中

python - 检查目录是否为空而不使用 os.listdir

python递归重命名目录

python - 如何在 PYTHON 中使用 CURL 命令

python - 替换分发版 python 脚本中的符号

python - python中哈希表/字典的实现

Python:方法 listdir 在哪里,因为模块 os.py 中没有 "def listdir()"?

python - 尝试从目录和子目录中查找所有 .txt 文件