(1)如下程式碼,預設遞迴取得指定目錄root_dir下的所有文件,當指定recursive參數為False時,則只取得root_dir目錄下的所有文件,不會遞歸的查找,若指定suffix_tuple參數,則可以取得root_dir目錄下的指定後綴檔案
from pathlib import Path def get_all_files(root_dir,recursive=True,suffix_tuple=()): all_files=[] if Path(root_dir).exists(): if Path(root_dir).is_dir(): if recursive: for elem in Path(root_dir).glob("**/*"): if Path(elem).is_file(): suffix=Path(elem).suffix if not suffix_tuple: all_files.append(elem) else: if suffix in suffix_tuple: all_files.append(elem) else: for elem in Path(root_dir).iterdir(): if Path(elem).is_file(): suffix=Path(elem).suffix if not suffix_tuple: all_files.append(elem) else: if suffix in suffix_tuple: all_files.append(elem) else: all_files.append(root_dir) return all_files
(2)具體使用方法如下,即測試程式碼,具體目錄path指定為自己存在的目錄
if __name__=="__main__": path="D:/gitee/oepkgs/mugen/testcases/cli-test/acl/oe_test_acl_defaulr_rule.sh" for elem in get_all_files(path): print(elem) print("-------------------------------------------------") path = "D:/gitee/oepkgs/mugen/testcases/cli-test/acl" for elem in get_all_files(path): print(elem) print("-------------------------------------------------") path = "D:/gitee/oepkgs/mugen/testcases/cli-test/acl" for elem in get_all_files(path,False): print(elem) print("-------------------------------------------------") path = "D:/gitee/oepkgs/mugen/testcases/cli-test/acl" for elem in get_all_files(path, True,(".sh",)): print(elem) print("-------------------------------------------------") path = "D:/gitee/oepkgs/mugen/testcases/cli-test/acl" for elem in get_all_files(path, True, (".json",)): print(elem)
執行結果如下,第一當指定path為文件時,直接將文件作為查詢到的返回,最後一個指定.json後綴,因為調試機上沒有json文件,所以打印為空
以上是Python代碼集pathlib應用如何取得指定目錄下的所有文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!