使用 os.walk() 在 Python 中递归遍历目录 [英] Using os.walk() to recursively traverse directories in Python

查看:65
本文介绍了使用 os.walk() 在 Python 中递归遍历目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从根目录导航到其中的所有其他目录并打印相同的内容.

这是我的代码:

#!/usr/bin/python导入操作系统导入 fnmatch对于 root、dir、os.walk(".") 中的文件:打印根打印 ""对于 fnmatch.filter(files, "*") 中的项目:打印..."+项目打印 ""

这是我的 O/P:

<预><代码>....Python_Notes...pypy.py...pypy.py.save...classdemo.py....goutputstream-J9ZUXW...最新.py...包.py...classdemo.pyc...Python_Notes~...模块演示.py...文件类型.py./packagedemo...classdemo.py...__init__.pyc...__init__.py...classdemo.pyc

上面,../packagedemo 是目录.

但是,我需要按以下方式打印 O/P:

A---a.txt---b.txt---乙------c.out

以上,AB为目录,其余为文件.

解决方案

这会给你想要的结果

#!/usr/bin/python导入操作系统# 遍历根目录,将目录列为目录,将文件列为文件对于 os.walk(".") 中的根、目录、文件:路径 = root.split(os.sep)print((len(path) - 1) * '---', os.path.basename(root))对于文件中的文件:打印(len(路径)*'---',文件)

I want to navigate from the root directory to all other directories within and print the same.

Here's my code:

#!/usr/bin/python

import os
import fnmatch

for root, dir, files in os.walk("."):
        print root
        print ""
        for items in fnmatch.filter(files, "*"):
                print "..." + items
        print ""

And here's my O/P:

.

...Python_Notes
...pypy.py
...pypy.py.save
...classdemo.py
....goutputstream-J9ZUXW
...latest.py
...pack.py
...classdemo.pyc
...Python_Notes~
...module-demo.py
...filetype.py

./packagedemo

...classdemo.py
...__init__.pyc
...__init__.py
...classdemo.pyc

Above, . and ./packagedemo are directories.

However, I need to print the O/P in the following manner:

A
---a.txt
---b.txt
---B
------c.out

Above, A and B are directories and the rest are files.

解决方案

This will give you the desired result

#!/usr/bin/python

import os

# traverse root directory, and list directories as dirs and files as files
for root, dirs, files in os.walk("."):
    path = root.split(os.sep)
    print((len(path) - 1) * '---', os.path.basename(root))
    for file in files:
        print(len(path) * '---', file)

这篇关于使用 os.walk() 在 Python 中递归遍历目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆