【问题标题】:Error while using listdir in Python在 Python 中使用 listdir 时出错
【发布时间】:2013-03-16 17:05:55
【问题描述】:

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

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”的子文件夹。有人可以帮我解决这个问题吗?

【问题讨论】:

  • 只是想知道这是否与 Windows 中的“/”有关!理想情况下,在 Windows 上,您应该有类似 os.path.join('C:','client_side') 的内容

标签: python file directory listdir


【解决方案1】:

当您在不引用现有路径的路径 上使用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)

返回一个列表,其中包含路径给定的目录中条目的名称。该列表是任意顺序的。它不包括特殊条目“。”和 '..' 即使它们存在于目录中。

os.path.isfile(path)

如果 path 是现有的常规文件,则返回 True。这遵循符号链接,因此 islink() 和 isfile() 对于同一路径都可以为真。

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)])

【讨论】:

  • 嗨。我现在没有任何 Windows 错误,但它始终将文件数输出为 0,尽管我在文件夹中有 7 个文件。你知道为什么吗?
  • @Sakura:因为os.listdir 返回名称。您不应在这些名称上使用 os.path.isfile。我更新了我的帖子并给出了完整的解释。
  • @Sakura 你真的应该改变接受的答案
  • 对于一般的操作系统操作,尝试除而不是 if else 会更好,因为可能同时发生其他文件操作。即try: os.listdir('/client_side/') except os.error: print("error listing directory")
【解决方案2】:

我决定把代码改成:

def numOfFiles(path):
    return len(next(os.walk(path))[2])

并使用以下调用代码:

print numOfFiles("client_side")

非常感谢所有告诉我如何在 Python 中正确传递 windows 目录以及here 中的 nrao91 提供函数代码的人。

编辑:感谢 eryksun 更正我的代码!

【讨论】:

  • 谢谢!我忘记了目录部分。我已经相应地更新了我的代码。
  • 不客气。 nymk's answer 非常好,我认为您应该接受它作为您问题的答案。
【解决方案3】:

两件事:

  1. os.listdir() 不进行 glob 模式匹配,请使用 glob 模块
  2. 可能您没有名为“/client_side/*.*”的目录,但可能有一个 名称中没有 .

如果您要查找的目录存在,但没有名为 '/client_side/.' 的目录,则您使用的语法可以正常工作。

此外,使用 Python 2.x 和 os.listdir 时要小心,因为使用 u'/client_side/' 和仅使用 '/client_side' 在 windows 上的结果是不同的。

【讨论】:

  • glob 由posix.listdir 添加。在 Win32 中,它使用 FindFirstFileW(或字节的 ANSI 版本)。它不允许尾部斜杠。因此,Python 不会像 C:\ 这样特殊的大小写根目录,而是附加 *.*
【解决方案4】:

你可以这样做

os.listdir('client_side')

没有斜线。

【讨论】:

  • 嗨。我现在没有任何 Windows 错误,但它始终将文件数输出为 0,尽管我在文件夹中有 7 个文件。你知道为什么吗?
【解决方案5】:

我可以看到WindowsError,只是想知道这是否与 Windows 中的“/”有关!理想情况下,在 Windows 上,您应该有类似 os.path.join('C:','client_side')

【讨论】:

    【解决方案6】:

    你想要:

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

    带有“.”在“/client_side/”之前。

    点表示您正在工作的当前路径(即从您调用代码的位置),因此“./client_side/”表示您想要的路径,它是相对于您当前目录指定的。

    如果您只写“/client_side/”,在 unix 中,程序会在系统根目录中查找文件夹,而不是您想要的文件夹。

    【讨论】:

      【解决方案7】:

      如果只想查看脚本所在目录下的所有文件,可以使用os.path.dirname(sys.argv[0])。这将给出脚本所在目录的路径。

      然后,使用fnmatch 函数,您可以获得该目录中具有在filename 变量中指定的名称和/或扩展名的文件列表。

      import os,sys
      from fnmatch import fnmatch
      
      directory = os.path.dirname(sys.argv[0])    #this determines the directory
      file_name= "*"                              #if you want the python files only, change "*" to "*.py"
      
      for path, subdirs, files in os.walk(directory):
          for name in files:
              if fnmatch(name, file_name):
                  print (os.path.join(path, name))
      

      我希望这会有所帮助。

      【讨论】:

        【解决方案8】:

        检查是否存在取决于比赛。更好地处理错误(请求宽恕而不是请求许可)。另外,在 Python 3 中,您可以抑制错误。使用 contextlib 中的抑制:

         with suppress(FileNotFoundError):
             for name in os.listdir('foo'):
                 print(name)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-08-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-23
          • 2017-04-13
          • 2020-03-07
          相关资源
          最近更新 更多