我有一個檔案夾,里面裝滿了數千個 .ai 檔案。該檔案夾的排列方式是它最初具有以客戶名稱命名的子檔案夾,并且在每個這些子檔案夾中都有一些或多個包含 .ai 的子檔案夾或包含 .ai 的 subs 內的子檔案夾中的子檔案夾的唯一目錄,或者沒有子檔案夾,只有 .ai 檔案。
我需要一個程式,該程式將通過獲取客戶子檔案夾中的每個 .ai 檔案名(無論有多少子檔案夾或 subs 中的 subs 等)來遍歷此檔案夾并將其附加到串列中。然后,我將獲取該串列并稍后對其進行一些 ocr 操作,但一旦完成,我將清除該串列并轉到下一個子檔案夾。
這是我曾經嘗試過的代碼,但失敗了。它有時會回傳一個空串列,或者其中只有一個檔案名的串列,而它每次都應該回傳一個串列,其中包含一個或多個 .ai 檔案名。
def folder_loop(folder):
temp_list = []
for root, dirs, files in os.walk(folder):
for dir in dirs:
for file in dir:
if file.endswith("ai"):
temp_list.append(os.path.join(root, file))
print(temp_list)
temp_list.clear()
我是一個初學者,我幾乎不明白代碼在做什么,所以我并不驚訝它沒有作業。有任何想法嗎?
uj5u.com熱心網友回復:
您可以嘗試以下方法:
如果您想為函式提供所有客戶檔案夾所在的基本檔案夾,然后希望為每個客戶檔案夾提供所有檔案的串列.ai
(來自每個子級別):
from pathlib import Path
def folder_loop(folder):
for path in Path(folder).iterdir():
if path.is_dir():
yield list(path.rglob("*.ai"))
Path.rglob("*.ai")
遞回地將給定及其所有子檔案夾用于-files。Path
.ai
要使用它:
the_folder = "..."
for file_list in folder_loop(the_folder):
print(file_list)
# do whatever you want to do with the files
如果你想給它一個檔案夾并想要一個包含所有.ai
檔案的串列:
def folder_loop(folder):
return list(Path(folder).rglob("*.ai"))
這里產生/回傳的串列包含Path
-objects(非常方便)。如果你想要字串,那么你可以做
....
yield list(map(str, path.rglob("*.ai")))
等等
uj5u.com熱心網友回復:
這里有一個社區帖子,其中有一些愚蠢的完整答案。
話雖如此,我的個人實用工具箱中有以下方法。
def get_files_from_path(path: str=".", ext=None) -> list:
"""Find files in path and return them as a list.
Gets all files in folders and subfolders
See the answer on the link below for a ridiculously
complete answer for this.
https://stackoverflow.com/a/41447012/9267296
Args:
path (str, optional): Which path to start on.
Defaults to '.'.
ext (str/list, optional): Optional file extention.
Defaults to None.
Returns:
list: list of full file paths
"""
result = []
for subdir, dirs, files in os.walk(path):
for fname in files:
filepath = f"{subdir}{os.sep}{fname}"
if ext == None:
result.append(filepath)
elif type(ext) == str and fname.lower().endswith(ext.lower()):
result.append(filepath)
elif type(ext) == list:
for item in ext:
if fname.lower().endswith(item.lower()):
result.append(filepath)
return result
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/470708.html