您可以使用`os.listdir()`函數(shù)來獲取目錄下的所有文件和子目錄,然后判斷返回的列表是否為空來判斷目錄是否為空。
下面是一個示例代碼:文章源自網(wǎng)吧系統(tǒng)維護-http://www.strong-digital.cn/11096.html
import os def is_directory_empty(path): return len(os.listdir(path)) == 0 # 測試示例 directory_path = "path/to/your/directory" if is_directory_empty(directory_path): print("目錄為空") else: print("目錄不為空")
在上面的示例中,您需要將"path/to/your/directory"替換為要判斷的目錄的實際路徑。`is_directory_empty()`函數(shù)會返回一個布爾值,如果目錄為空則返回True,否則返回False。在示例中,根據(jù)返回值打印相應(yīng)的提示信息。文章源自網(wǎng)吧系統(tǒng)維護-http://www.strong-digital.cn/11096.html
請注意,`os.listdir()`函數(shù)還會返回一些特殊文件,比如"."(表示當前目錄)和".."(表示上級目錄),因此在判斷目錄是否為空時需要特別注意。文章源自網(wǎng)吧系統(tǒng)維護-http://www.strong-digital.cn/11096.html 文章源自網(wǎng)吧系統(tǒng)維護-http://www.strong-digital.cn/11096.html
版權(quán)聲明:文章圖片資源來源于網(wǎng)絡(luò),如有侵權(quán),請留言刪除!!!
評論