[英]How to check to see if a folder contains files using python 3
我到處搜索這個答案,但找不到。
我試圖想出一個腳本來搜索特定的子文件夾,然后檢查它是否包含任何文件,如果是,寫出文件夾的路徑。 我已經弄清楚了子文件夾搜索部分,但是文件檢查讓我很困惑。
我找到了關於如何檢查文件夾是否為空的多個建議,並且我嘗試修改腳本以檢查文件夾是否為空,但我沒有得到正確的結果。
這是最接近的腳本:
for dirpath, dirnames, files in os.walk('.'):
if os.listdir(dirpath)==[]:
print(dirpath)
這將列出所有空的子文件夾,但如果我嘗試將其更改為:
if os.listdir(dirpath)!=[]:
print(dirpath)
它將列出所有內容——而不僅僅是那些包含文件的子文件夾。
如果有人能指出我正確的方向,我將不勝感激。
如果這很重要,這適用於 Python 3.4。
感謝你給與我的幫助。
'files' 已經告訴你目錄中的內容。 只需檢查一下:
for dirpath, dirnames, files in os.walk('.'):
if files:
print(dirpath, 'has files')
if not files:
print(dirpath, 'is empty')
添加到@Jon Clements 的 pathlib 答案中,我想使用 pathlib 檢查文件夾是否為空,但不創建集合:
from pathlib import Path
# shorter version from @vogdb
is_empty = not any(Path('some/path/here').iterdir())
# similar but unnecessary complex
is_empty = not bool(sorted(Path('some/path/here').rglob('*')))
vogdb 方法嘗試遍歷給定目錄中的所有文件。 如果沒有文件,any() 將為 False。 我們用 not 否定它,所以 is_empty 如果沒有文件則為 True,如果有文件則為 False。
sorted(Path(path_here).rglob('*')) 返回已排序 PosixPah 項目的列表。 如果沒有項目,則返回一個空列表,即 False。 因此,如果路徑為空,則 is_empty 將為 True,如果路徑有內容則為 false
類似的想法結果 {} 和 [] 給出了相同的結果:
您可以利用 Python 3.4 中引入的新pathlib
庫遞歸提取所有非空子目錄,例如:
import pathlib
root = pathlib.Path('some/path/here')
non_empty_dirs = {str(p.parent) for p in root.rglob('*') if p.is_file()}
由於無論如何您都必須遍歷樹,因此我們構建了一組存在文件的父目錄,這會導致一組包含文件的目錄 - 然后按照您的意願處理結果。
如果可以刪除目錄,則可以使用以下命令:
my_path = os.path.abspath("something")
try:
os.rmdir(my_path)
is_empty = True
# Do you need to keep the directory? Recreate it!
# os.makedirs(my_path, exist_ok=True)
except OSError:
is_empty = False
if is_empty:
pass
os.rmdir僅在目錄為空時刪除目錄,否則會引發 OSError 異常。
您可以在以下位置找到有關此問題的討論:
例如,當您計划執行 git clone 時刪除一個空目錄是可以的,但如果您事先檢查目錄是否為空,則刪除一個空目錄就沒有問題,因此您的程序不會拋出空目錄錯誤。
檢查文件夾是否包含文件:
import os
import shutil
if len(os.listdir(folder_path)) == 0: # Check is empty..
shutil.rmtree(folder_path) # Delete..
entities = os.listdir(dirpath)
for entity in entities:
if os.path.isfile(entity):
print(dirpath)
break
使用pathlib
可以按如下方式完成:
import pathlib
# helper function
def is_empty(_dir: pathlib.PAth) -> bool:
# return not bool([_ for _ in _dir.iterdir()])
return not any(_dir.iterdir())
# create empty dir
_dir = pathlib.Path("abc")
# check if dir empty
is_empty(_dir) # will retuen True
# add file s to folder and call it again
您可以使用這個簡單的代碼:
dir_contents = [x for x in os.listdir('.') if not x.startswith('.')]
if len(dir_contents) > 0:
print("Directory contains files")
它檢查當前工作目錄 ( .
) 中的文件和目錄。 你可以改變.
在os.listdir()
中檢查任何其他目錄。
這現在可以在Python3.5+ 中更有效地完成,因為不需要構建目錄內容列表來查看它是否為空:
import os
def is_dir_empty(path):
with os.scandir(path) as scan:
return next(scan, None) is None
我跟隨Bash 檢查文件夾是否有內容答案。
os.walk('.')
返回一個目錄下的完整文件,如果有數千個它可能效率低下。 而是按照命令find "$target" -mindepth 1 -print -quit
返回第一個找到的文件並退出。 如果它返回一個空字符串,這意味着文件夾是空的。
您可以使用
find
檢查目錄是否為空,並處理其輸出
def is_dir_empty(absolute_path):
cmd = ["find", absolute_path, "-mindepth", "1", "-print", "-quit"]
output = subprocess.check_output(cmd).decode("utf-8").strip()
return not output
print is_dir_empty("some/path/here")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.