用法:
os.scandir(path='.')返回與
path給出的目錄中的條目相對應的os.DirEntry對象的迭代器。條目按任意順序生成,不包括特殊條目'.'和'..'。如果在創建迭代器後從目錄中刪除或添加文件,則未指定是否包含該文件的條目。使用
scandir()而不是listdir()可以顯著提高還需要文件類型或文件屬性信息的代碼的性能,因為如果操作係統在掃描目錄時提供了這些信息,os.DirEntry對象就會公開這些信息。所有os.DirEntry方法都可以執行係統調用,但is_dir()和is_file()通常隻需要對符號鏈接進行係統調用;os.DirEntry.stat()在 Unix 上總是需要一個係統調用,但在 Windows 上隻需要一個用於符號鏈接。path可能是path-like 對象。如果path的類型為bytes(直接或間接通過PathLike接口),則每個os.DirEntry的name和path屬性的類型將為bytes;在所有其他情況下,它們將是類型str。該函數還可以支持指定文件說明符;文件說明符必須引用一個目錄。
使用參數
path引發審計事件os.scandir。scandir()迭代器支持上下文管理器協議,具有以下方法:-
scandir.close() 關閉迭代器並釋放獲取的資源。
當迭代器耗盡或垃圾收集時,或者在迭代過程中發生錯誤時,它會自動調用。但是,建議顯式調用它或使用
with語句。3.6 版中的新函數。
以下示例顯示了
scandir()的簡單用法,以顯示給定path中不以'.'開頭的所有文件(不包括目錄)。entry.is_file()調用通常不會進行額外的係統調用:with os.scandir(path) as it: for entry in it: if not entry.name.startswith('.') and entry.is_file(): print(entry.name)注意
在基於 Unix 的係統上,
scandir()使用係統的 opendir() 和 readdir() 函數。在 Windows 上,它使用 Win32 FindFirstFileW 和 FindNextFileW 函數。3.5 版中的新函數。
3.6 版中的新函數:增加了對上下文管理器協議和
close()方法。如果一個os.scandir迭代器既沒有耗盡也沒有明確關閉ResourceWarning將在其析構函數中發出。該函數接受 path-like 對象。
在 3.7 版中更改:增加了對文件說明符在 Unix 上。
-
相關用法
- Python os.scandir()用法及代碼示例
- Python os.sched_setaffinity()用法及代碼示例
- Python os.sched_getaffinity()用法及代碼示例
- Python os.sched_get_priority_max()用法及代碼示例
- Python os.sched_get_priority_min()用法及代碼示例
- Python os.sched_rr_get_interval()用法及代碼示例
- Python os.set_blocking()用法及代碼示例
- Python os.setregid()用法及代碼示例
- Python os.strerror()用法及代碼示例
- Python os.spawnl用法及代碼示例
- Python os.set_inheritable()用法及代碼示例
- Python os.system()用法及代碼示例
- Python os.setreuid()用法及代碼示例
- Python os.statvfs()用法及代碼示例
- Python os.symlink()用法及代碼示例
- Python os.sync()用法及代碼示例
- Python os.stat()用法及代碼示例
- Python os.sendfile()用法及代碼示例
- Python os.setgroups()用法及代碼示例
- Python os.sysconf()用法及代碼示例
注:本文由純淨天空篩選整理自python.org大神的英文原創作品 os.scandir。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
