使用os.walk()以递归方式遍历Python中的目录我想从根目录导航到其中的所有其他目录并打印相同的目录。这是我的代码:#!/usr/bin/pythonimport osimport fnmatchfor 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是目录,其余的文件。
3 回答

拉丁的传说
TA贡献1789条经验 获得超8个赞
这将为您提供所需的结果
#!/usr/bin/pythonimport os# traverse root directory, and list directories as dirs and files as filesfor 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)
添加回答
举报
0/150
提交
取消