Python--遍歷文件夾下所有文件和目錄的方法(os.walk(rootdir)函數返回一個三元素元祖)


 1 import os
 2 import os.path
 3 
 4 # This folder is custom
 5 rootdir = '/Users/macbookpro/Desktop/test'
 6 for parent, dirnames, filename in os.walk(rootdir):
 7     # Case1: traversal the directories
 8     for dirname in dirnames:
 9         print("Parent folder:", parent)
10         print("Dirname:", filename)
11     # Case2: traversal the files
12     for filename in filenames:
13         print("Parent folder:", parent)
14         print("Filename:", filename)


 

解釋說明:os.walk(rootdir)函數返回一個三元素元祖,其中parent是父目錄,dirnames是所有文件夾名字(不包含路徑),filenames是所有文件的名字(不包含路徑)

以上,case1、case2分別演示了遍歷該文件夾下(/Users/macbookpro/Desktop/test)的所有目錄、文件的方法

效果圖如下

 



原文:https://blog.csdn.net/abc_12366/article/details/79845500
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM