【问题标题】:Why is os.walk() not defining dirs or files?为什么 os.walk() 没有定义目录或文件?
【发布时间】:2017-08-05 08:29:19
【问题描述】:

我在 Python 2.7 中有这段代码:

# !/usr/bin/python

import os
root=os.path.normpath('/home/andreas/Desktop/')

print root
for root, dirs,files in os.walk(root, topdown=True):
    break   
print(files)

哪个有效。它返回一个包含 Desktop 中文件名的列表。 但是当我改变路径时:

 root=os.path.normpath('/home/andreas/Desktop/Some_Dir')

我收到此错误:

NameError: name 'files' is not defined

这也适用于dirs

可能是什么问题?

【问题讨论】:

  • 无法复制...
  • 只是好奇:为什么会在没有任何条件的情况下将 break 放入 for 循环?

标签: python linux python-2.7 undefined os.walk


【解决方案1】:

如果dirsfilesfor 循环终止后没有定义,这意味着os.walk() 没有产生任何结果——这意味着它们从未被分配任何值,因此保持未定义。

这是一个相同效果的简单示例:

>>> for x in []:  # empty
...     pass
... 
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

>>> for x in [1, 2, 3]:
...     pass
... 
>>> x
3

os.walk(some_path) 没有产生任何结果的明显解释是 some_path 不存在或无法访问......所以大概你没有Some_Dir,或者你没有获得许可操作系统来访问它。

例如:

$ mkdir nope
$ chmod a-rwx nope
$ python
Python 2.7.13 (default, Jan 13 2017, 10:15:16) 
[GCC 6.3.1 20161221 (Red Hat 6.3.1-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> for root, dirs, files in os.walk('nope'):
...     break
... 
>>> dirs
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'dirs' is not defined
>>> files
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'files' is not defined
>>> 

【讨论】:

  • 无法使用os.walk 进行复制,可以吗? (我使用的是 v3.4)
  • 好的,我明白了,但是我该如何解决这个问题?因为文件夹不为空
  • @adrian.andreas 检查拼写错误或权限问题。
  • @ZeroPiraeus 你是对的,如果目录不存在,没有异常并且没有定义变量;奇怪!
  • @Jean-FrançoisFabre 是的,这不是最直观的行为。
猜你喜欢
  • 1970-01-01
  • 2020-04-02
  • 1970-01-01
  • 2021-08-29
  • 2017-10-28
  • 2011-07-05
  • 2013-11-23
  • 2019-05-23
  • 2018-02-11
相关资源
最近更新 更多