python 兩種方法刪除空文件夾
更新時間:2020年09月29日 16:00:33 作者:mentiantian
這篇文章主要介紹了python 兩種方法刪除空文件夾,幫助大家更好的利用python處理文件,感興趣的朋友可以了解下
第一種方法:
import os
def delete_gap_dir(dir):
if os.path.isdir(dir):
for d in os.listdir(dir):
#print('1',os.path.join(dir, d))
path = os.path.join(dir, d)
if os.path.isdir(path) and not path.endswith('pic_neg'):
delete_gap_dir(path)
if not os.listdir(dir):
#print('空文件夾:' + dir)
os.rmdir(dir)
print('移除空目錄: ' + dir)
#else:
#print(dir)
# delete_gap_dir(os.getcwd())
if __name__ == "__main__":
dir = r'C:\newpython\123'
delete_gap_dir(dir)
print(u'刪除完畢')
效果


第二種方法:
import os
def del_emp_dir(path):
for (root, dirs, files) in os.walk(path):
for item in dirs:
dir = os.path.join(root, item)
try:
os.rmdir(dir) #os.rmdir() 方法用于刪除指定路徑的目錄。僅當(dāng)這文件夾是空的才可以, 否則, 拋出OSError。
print(dir)
except Exception as e:
print('Exception',e)
if __name__ == '__main__':
dir = r'F:\test'
del_emp_dir(dir)
以上就是python 兩種方法刪除空文件夾的詳細(xì)內(nèi)容,更多關(guān)于python 刪除文件夾的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python圖形界面開發(fā)之wxPython樹控件使用方法詳解
這篇文章主要介紹了python圖形界面開發(fā)之wxPython樹控件使用方法詳解,需要的朋友可以參考下2020-02-02
解決jupyter notebook 出現(xiàn)In[*]的問題
這篇文章主要介紹了解決jupyter notebook 出現(xiàn)In[*]的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Python基礎(chǔ)知識學(xué)習(xí)之類的繼承
今天帶大家學(xué)習(xí)Python的基礎(chǔ)知識,文中對python類的繼承作了非常詳細(xì)的介紹,對正在學(xué)習(xí)python基礎(chǔ)的小伙伴們很有幫助,需要的朋友可以參考下2021-05-05
Python身份運算符is與is?not區(qū)別用法基礎(chǔ)教程
這篇文章主要為大家介紹了Python身份運算符is與is?not區(qū)別用法基礎(chǔ)教程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
django.db.utils.ProgrammingError: (1146, u“Table‘’ doesn’t e
這篇文章主要給大家介紹了關(guān)于執(zhí)行python manage.py migrate時報錯:django.db.utils.ProgrammingError: (1146, "Table 'test.model_student' doesn't exist" )問題的解決方法,文中將解決的方法介紹的非常詳細(xì),需要的朋友可以參考下2018-07-07
Python初學(xué)時購物車程序練習(xí)實例(推薦)
下面小編就為大家?guī)硪黄狿ython初學(xué)時購物車程序練習(xí)實例(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08

