我想从根目录导航到所有其他目录,并打印相同的内容。
这是我的代码:
#!/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是目录,其余是文件。
假设你有一个任意的父目录,子目录如下:
/home/parent_dir
├── 0_N
├── 1_M
├── 2_P
├── 3_R
└── 4_T
下面是你可以估计每个子目录中#文件相对于父目录中#文件总数的大致百分比:
from os import listdir as osl
from os import walk as osw
from os.path import join as osj
def subdir_summary(parent_dir):
parent_dir_len = sum([len(files) for _, _, files in osw(parent_dir)])
print(f"Total files in parent: {parent_dir_len}")
for subdir in sorted(osl(parent_dir)):
subdir_files_len = len(osl(osj(parent_dir, subdir)))
print(subdir, subdir_files_len, f"{int(100*(subdir_files_len / parent_dir_len))}%")
subdir_summary("/home/parent_dir")
它将在终端中打印如下:
Total files in parent: 5876
0_N 3254 55%
1_M 509 8%
2_P 1187 20%
3_R 594 10%
4_T 332 5%
试试这个吧;简单的
#!/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