Python os.path.walk() 方法

标签 python

我目前在 uni 作业中使用 walk 方法。一切正常,但我希望有人能向我解释一些事情。

在下面的示例中,myvisit 方法中使用的 a 参数是什么?

>>> from os.path import walk
>>> def myvisit(a, dir, files):
...   print dir,": %d files"%len(files)

>>> walk('/etc', myvisit, None)
/etc : 193 files
/etc/default : 12 files
/etc/cron.d : 6 files
/etc/rc.d : 6 files
/etc/rc.d/rc0.d : 18 files
/etc/rc.d/rc1.d : 27 files
/etc/rc.d/rc2.d : 42 files
/etc/rc.d/rc3.d : 17 files
/etc/rc.d/rcS.d : 13 files

最佳答案

回调函数的第一个参数是 os.path.walk 函数的最后一个参数。它最明显的用途是允许您在连续调用辅助函数(在您的情况下为 myvisit)之间保持状态。

os.path.walk 是一个已弃用的函数。您确实应该使用 os.walk,它不需要回调函数或辅助参数(例如示例中的 a)。

for directory, dirnames, filenames in os.walk(some_path):
    # run here your code

关于Python os.path.walk() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2934281/

相关文章:

python - python中等效的C/C++ losose算法是什么

Python:Jupyter Notebook 创建运行代码的动态检查表用户输入

python - 值错误 : cannot set toolkit to wx because it has already been set to qt4

python - Pandas isin 在使用 concat 后遇到空 DF 时返回错误

python - 检索一行 2 for 循环内最里面的值?

尝试读取图像元数据时,Python XMP Toolkit 过于严格 ("Unrecognized TIFF prefix")

python - 我的表单被调用了两次,但为什么呢?

python - 我在 shell 脚本中运行一个程序。我怎么知道它是否已加载? (Linux)

python - pygtk 应用程序中的单独线程

python - 如何制作带有未定义区域的彩色图?