我厭倦了這個:
import os
for file in os.listdir("D:\\Python\\Projects\\p1"):
if file.endswith(".py"):
print(os.path.join("/Python files:", file))
但這只會給我一個檔案夾中的檔案,但我想要所有檔案夾的所有 py 檔案,例如:p1 有子檔案夾,其中有一些 py 檔案,而那些子檔案夾有一些 py 檔案,依此類推 “p1-->sub_folder-- >sub_folder--->sub_folder" 所以,我需要獲取所有檔案夾和子檔案夾中的所有py檔案。
任何幫助/建議都會對我有很大幫助,謝謝
uj5u.com熱心網友回復:
您可以使用rglob 函式:
from pathlib import Path
for one_file in Path("D:\\Python\\Projects\\p1").rglob("*.py"):
print(one_file)
編輯:
如果您需要避免使用子檔案夾,您可以執行以下操作:
from pathlib import Path
for one_file in Path("D:\\Python\\Projects\\p1").rglob("*.py"):
if "venv" not in one_file.parts:
print(one_file)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/444915.html
標籤:Python
