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

Rol*_*lex 4 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))] 
Run Code Online (Sandbox Code Playgroud)

第一行工作:

[x for x in os.listdir('.') if os.path.isfile(x)]
Run Code Online (Sandbox Code Playgroud)

但接下来的两个:

[x for x in os.listdir('dirname') if os.path.isfile(x)]
Run Code Online (Sandbox Code Playgroud)

[x for x in os.listdir(os.path.abspath('dirname')) if os.path.isfile(os.path.abspath(x))] 
Run Code Online (Sandbox Code Playgroud)

只是输出 []

为什么?

Ana*_*mar 6

因为需要加入dirnamewith xos.listdir()直接列出内容即可,内容没有全路径。

例子 -

[x for x in os.listdir('dirname') if os.path.isfile(os.path.join('dirname',x))]
Run Code Online (Sandbox Code Playgroud)

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


例子 -

让我们说一些文件夹 - /a/b/c- 有文件 -xy在其中。

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

['x','y']
Run Code Online (Sandbox Code Playgroud)

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


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

os.path.abspath('somefile')
Run Code Online (Sandbox Code Playgroud)

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

它在文档中明确说明(强调我的) -

os.path.abspath(路径)

返回路径名路径的规范化绝对化版本。在大多数平台上,这相当于调用函数normpath()如下:normpath(join(os.getcwd(), path))

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