Skip to main content
 首页 » 编程设计

python之解包不同文件路径的 os.walk 不一致错误

2025年05月04日14JustinYoung

基本的 Python 问题。

正在使用 os.walk 函数,看到不一致的错误消息。 以下示例 o/p:

Python 3.6.2 (default, Jul 18 2017, 14:08:57) 
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import os 
>>> root, dir, files = os.walk('.')  # ------> **no error** 
>>> root, dir, files = os.walk('/')  # ------> **error #1** 
Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
ValueError: too many values to unpack (expected 3) 
>>> root, dir, files = os.walk('/usr/bin') # ------>**error #2** 
Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
ValueError: not enough values to unpack (expected 3, got 1) 
>>> 

我的理解是 os.walk 返回生成器,所以错误 #2 对我来说很有意义。返回一个生成器值,但我解包为 3 个值。

所以:

  1. 为什么我在 os.walk('.')
  2. 时没有收到任何错误
  3. 为什么错误 #2 和 #1 不同。

编辑 1:

玩了一下,发现python运行的位置影响了执行,因为“.”的意思。变化。

raghu$ pwd 
/Users/raghu/PycharmProjects/Fib 
raghu$ python 
Python 3.6.2 (default, Jul 18 2017, 14:08:57) 
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import os 
>>> root, dir, files = os.walk('.')  # ------>**no error** 
>>> ^D 
raghu$ cd .. 
raghu$ pwd 
/Users/raghu/PycharmProjects 
raghu$ python 
Python 3.6.2 (default, Jul 18 2017, 14:08:57) 
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import os 
>>> root, dir, files = os.walk('.')  # ------>**error** 
Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
ValueError: too many values to unpack (expected 3) 

请您参考如下方法:

当你解包时,你耗尽了右边的可迭代对象。你没有得到 dirpath, dirname, filenames您分配给 root, dirs, filenames 的元组.

尝试分配 os.walk(<value) 的第一个结果(即第一个 yield )至 root完成了,那么,第二个结果(second yield)为dirs然后,最后,第三个 yield 为 file .如果产生更多(或更少!)的结果,就会出现错误。如果恰好返回三个,它似乎有效。

所以,在第一种情况下,这只是运气和 3返回给你的结果已分配( 3 包含 dirpath, dirname, filenames 的元组!)。

'/usr/bin' 通常 不包含任何子目录,这就是为什么会出现不同的错误(只执行 1 个三元组 yield)。

与 '/'您还会返回更多数量的三元素元组,因此您会得到相应的错误。

您可以通过检查生成器生成的项目数量来大致了解一下:

>>> from os import walk 
>>> len(list(walk('.'))) 
2300 
>>> len(list(walk('/')))  # this is really dumb 
127242 
>>> len(list(walk('/usr/bin'))) 
1 

正如您在最后一个示例中看到的,只生成了一个 3 元素元组。如果您找到一个文件夹,其 len(list(walk('folder'))) == 3 , 解包将起作用。