python - 在 Python 中使用 listdir 时出错

标签 python file directory listdir

我正在尝试获取特定目录中的文件列表并计算该目录中的文件数。我总是收到以下错误:

WindowsError: [Error 3] The system cannot find the path specified: '/client_side/*.*'

我的代码是:

print len([name for name in os.listdir('/client_side/') if os.path.isfile(name)])

我按照给定的代码示例 here .

我正在 Pyscripter 上运行 Python 脚本,目录/client_side/确实存在。我的 python 代码位于根文件夹中,并且有一个名为“client_side”的子文件夹。有人可以帮我解决这个问题吗?

最佳答案

当您在未引用现有路径的路径 上使用os.listdir 时会发生此错误。
例如:

>>> os.listdir('Some directory does not exist')
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
WindowsError: [Error 3] : 'Some directory does not exist/*.*'

如果你想使用os.listdir,你需要保证你要使用的路径存在,或者使用os.path.exists来检查存在第一。

if os.path.exists('/client_side/'):
    do something
else:
    do something

假设你当前的工作目录是c:\foobaros.listdir('/client_side/')等同于os.listdir('c :/client_side'),而 os.listdir('client_side/') 等同于 os.listdir('c:/foobar/client_side') .如果你的 client_side 目录不在根目录下,那么在使用 os.listdir 时会出现这样的错误。

对于您的 0 输出问题,让我们记忆一下 os.listdir(path)

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

os.path.isfile(path) .

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

listdir 既不返回绝对路径也不返回相对路径,而是返回文件名列表,而 isfile 需要路径。因此,所有这些名称都会产生 False

要获取路径,我们可以使用os.path.join , 直接连接两个字符串。

print ([name for name in os.listdir(path)
        if os.path.isfile(os.path.join(path, name))])

或者

print ([name for name in os.listdir('client_side/')
        if os.path.isfile('client_side/' + name)])

关于python - 在 Python 中使用 listdir 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15452099/

相关文章:

python - 使用伪文件将空文件上传到ftp

python - 根据最大值和最小值填写缺失的日期 pandas

Java 添加组到目录权限列表

java - isDirectory() 为文件返回 true

c - 从 C 程序粉碎和删除 linux 中的文件

c++ - 带有子目录的 CMake

python - 根据特定列的值计数添加/删除行

python - 在 for-else 循环中是否存在与 "else"相反的行为?

c++ - 在 C++ 中删除部分文件的最快方法

c# - 在 C# 中创建一个文件并将其作为 IntPtr 传递给 COM 对象