我想从根目录导航到所有其他目录,并打印相同的内容。
这是我的代码:
#!/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是目录。
不过,我需要以下列方式列印订单:
A
---a.txt
---b.txt
---B
------c.out
上面,A和B是目录,其余是文件。
试试这个吧;简单的
#!/usr/bin/python
import os
# Creating an empty list that will contain the already traversed paths
donePaths = []
def direct(path):
for paths,dirs,files in os.walk(path):
if paths not in donePaths:
count = paths.count('/')
if files:
for ele1 in files:
print '---------' * (count), ele1
if dirs:
for ele2 in dirs:
print '---------' * (count), ele2
absPath = os.path.join(paths,ele2)
# recursively calling the direct function on each directory
direct(absPath)
# adding the paths to the list that got traversed
donePaths.append(absPath)
path = raw_input("Enter any path to get the following Dir Tree ...\n")
direct(path)
输出= = = = = = = = = = = = = = = =
/home/test
------------------ b.txt
------------------ a.txt
------------------ a
--------------------------- a1.txt
------------------ b
--------------------------- b1.txt
--------------------------- b2.txt
--------------------------- cde
------------------------------------ cde.txt
------------------------------------ cdeDir
--------------------------------------------- cdeDir.txt
------------------ c
--------------------------- c.txt
--------------------------- c1
------------------------------------ c1.txt
------------------------------------ c2.txt
你也可以使用pathlib.Path()递归地遍历一个文件夹并列出它的所有内容
from pathlib import Path
def check_out_path(target_path, level=0):
""""
This function recursively prints all contents of a pathlib.Path object
"""
def print_indented(folder, level):
print('\t' * level + folder)
print_indented(target_path.name, level)
for file in target_path.iterdir():
if file.is_dir():
check_out_path(file, level+1)
else:
print_indented(file.name, level+1)
my_path = Path(r'C:\example folder')
check_out_path(my_path)
输出:
example folder
folder
textfile3.txt
textfile1.txt
textfile2.txt