python 遍歷磁盤目錄的三種方法
import osdef get_files(path): # 判斷路徑是否存在,如果不存在,函數(shù)直接結(jié)束 if not os.path.exists(path): print(’路徑不存在’) return # 判斷路徑是否為文件夾 if not os.path.isdir(path): print(’路徑是一個(gè)文件’) return # 這時(shí)候,路徑是一個(gè)文件夾 # 獲取文件夾中文件或文件夾的名稱 file_list = os.listdir(path) # 遍歷文件夾 for filename in file_list: # 拼接路徑,獲取每個(gè)次級(jí)目錄下的文件路徑 subpath = os.path.join(path,filename) if os.path.isfile(subpath): if os.path.splitext(subpath)[1] == ’.py’:print(’python文件:{}’.format(subpath)) else: # 如果filename是文件夾,則調(diào)用函數(shù)繼續(xù)遍歷 get_files(subpath)用棧來遍歷磁盤
棧的特點(diǎn):先進(jìn)后廚,后進(jìn)先出原理:path第一次被pop刪除后返回path,遍歷目錄下的文件,如果遇到文件夾追加到列表中,pop是刪除最后一位的元素,每次又遍歷最后一位的文件夾,所以每一輪都會(huì)將次級(jí)目錄下的文件夾遍歷完成之后再遍歷下個(gè)次級(jí)目錄
import osdef get_files(path): # 判斷路徑是否存在 if not os.path.exists(path): print(’路徑不存在’) return if not os.path.isdir(path): print(’路徑是一個(gè)文件夾’) return # 創(chuàng)建一個(gè)列表作為棧 stack = [path] # 取出棧中的元素 while len(stack) != 0: path = stack.pop() file_list = os.listdir(path) for filename in file_list: subpath = os.path.join(path,filename) if os.path.isfile(subpath):print(’python文件:{}’.format(subpath)) else:stack.append(subpath)廣度遍歷磁盤用隊(duì)列遍歷磁盤
import osimport collectionsdef get_py_file(path): # 判斷路徑是否存在 if not os.path.exists(path): print(’路徑不存在’) return # 判斷路徑是否是文件夾 if os.path.isfile(path): print(’路徑是文件’) return # path是一個(gè)文件夾 # 定義一個(gè)空對(duì)列 queue = collections.deque() queue.append(path) while len(queue) != 0: # 從隊(duì)列中獲取第一個(gè)元素 path = queue.popleft() # 獲取目錄下的所有內(nèi)容 filelist = os.listdir(path) # 遍歷 for filename in filelist: # 拼接 filepath = os.path.join(path, filename) if os.path.isfile(filepath):if os.path.splitext(filepath)[1] == ’.py’: print(filepath) else:queue.append(filepath)
以上就是python 遍歷磁盤目錄的三種方法的詳細(xì)內(nèi)容,更多關(guān)于python 遍歷磁盤目錄的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 讓chatgpt將html中的圖片轉(zhuǎn)為base64方法示例2. asp畫中畫廣告插入在每篇文章中的實(shí)現(xiàn)方法3. 使用純HTML的通用數(shù)據(jù)管理和服務(wù)4. ASP編碼必備的8條原則5. asp中Request.ServerVariables的參數(shù)集合6. WMLScript腳本程序設(shè)計(jì)第1/9頁7. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera8. PHP反序列化漏洞實(shí)例深入解析9. ASP基礎(chǔ)知識(shí)Command對(duì)象講解10. PHP session反序列化漏洞深入探究
