您好,登錄后才能下訂單哦!
這篇“Python怎么獲取指定目錄下的所有文件”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“Python怎么獲取指定目錄下的所有文件”文章吧。
(1)如下代碼,默認(rèn)遞歸獲取指定目錄root_dir下的所有文件,當(dāng)指定recursive參數(shù)為False時(shí),則只獲取root_dir目錄下的所有文件,不會(huì)遞歸的查找,若指定suffix_tuple參數(shù),則可以獲取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)具體使用方法如下,即測(cè)試代碼,具體目錄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)
執(zhí)行結(jié)果如下,第一個(gè)當(dāng)指定path為文件時(shí),則直接將文件作為查詢到的返回,最后一個(gè)指定.json后綴,因?yàn)檎{(diào)試機(jī)上沒有json文件,所以打印為空
以上就是關(guān)于“Python怎么獲取指定目錄下的所有文件”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。