我想从根目录导航到其中的所有其他目录并打印相同的内容。
这是我的代码:
#!/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 ""
这是我的 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
上面,.
和./packagedemo
都是目录。
但是,我需要按以下方式打印 O/P:
A
---a.txt
---b.txt
---B
------c.out
上面,A
和B
是目录,其余都是文件。
最佳答案
这会给你想要的结果
#!/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)
关于python - Python中使用os.walk()递归遍历目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16953842/