python刪除目錄的三種方法
更新時間:2024年12月08日 11:42:46 作者:hakesashou
本文主要介紹了python刪除目錄的三種方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
一、os.rmdir(path)
刪除目錄 path,path必須是個空目錄,否則拋出OSError異常。
import os os.rmdir('./test') # test是一個空的文件夾
二、os.removedirs(path)
遞歸地刪除目錄。要求每一級目錄都為空,才能遞歸刪除全部目錄。子目錄被成功刪除,才刪除父目錄;如果子目錄沒有成功刪除,將拋出OSError異常。
import os #test2是test的子文件夾,如果test2不為空,則拋出異常;如果test2為空,test不為空,則test2刪除成功,test不刪除,但不報異常 os.removedirs('./test/test2)
三、shutil.rmtree(path)
不管目錄path是否為空,都刪除。
import shutil shutil.rmtree('./test') # 刪除test文件夾下所有的文件、文件夾
四、刪除文件
Pathlib
from pathlib import Path # 定義要刪除的文件路徑 file_to_delete = Path('/home/python/test/file1.txt') try: # 檢查文件是否存在 if file_to_delete.exists() and file_to_delete.is_file(): # 刪除文件 file_to_delete.unlink() print(f"File {file_to_delete} has been deleted.") else: print(f"File {file_to_delete} does not exist or is not a file.") except Exception as e: print(f"An error occurred: {e}")
os
import os # 定義要刪除的文件路徑 file_to_delete = '/home/python/test/file1.txt' try: # 檢查文件是否存在 if os.path.exists(file_to_delete) and os.path.isfile(file_to_delete): # 刪除文件 os.remove(file_to_delete) print(f"File {file_to_delete} has been deleted.") else: print(f"File {file_to_delete} does not exist or is not a file.") except Exception as e: print(f"An error occurred: {e}")
到此這篇關(guān)于python刪除目錄的三種方法的文章就介紹到這了,更多相關(guān)python刪除目錄內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Tensorflow使用tfrecord輸入數(shù)據(jù)格式
這篇文章主要介紹了Tensorflow使用tfrecord輸入數(shù)據(jù)格式,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06ubuntu系統(tǒng)下多個python版本如何設(shè)置默認python和pip
pip是一個用來安裝Python軟件包的工具,下面這篇文章主要給大家介紹了關(guān)于ubuntu系統(tǒng)下多個python版本如何設(shè)置默認python和pip的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2023-12-12