使用python刪除一個檔案或檔案夾

來源:互聯網
上載者:User

標籤:remove   檔案的   false   erro   檔案夾路徑   link   color   文本   刪除目錄   

使用python刪除一個檔案或檔案夾,需要使用os模組。

import os
os.remove(path) # path是檔案的路徑,如果這個路徑是一個檔案夾,則會拋出OSError的錯誤,這時需用用rmdir()來刪除
os.rmdir(path) # path是檔案夾路徑,注意檔案夾需要時空的才能被刪除
os.unlink(‘F:\建立文字文件.txt‘) # unlink的功能和remove一樣是刪除一個檔案,但是刪除一個刪除一個正在使用的檔案會報錯。
import ospath = ‘F:/建立文字文件.txt‘  # 檔案路徑if os.path.exists(path):  # 如果檔案存在    # 刪除檔案,可使用以下兩種方法。    os.remove(path)      #os.unlink(path)else:    print(‘no such file:%s‘%my_file)  # 則返迴文件不存在
import os
os.removedirs(path) # 遞迴地刪除目錄。如果子目錄成功被刪除,則將會成功刪除父目錄,子目錄沒成功刪除,將拋異常。
import osfor root, dirs, files in os.walk(top, topdown=False):    for name in files:        os.remove(os.path.join(root, name))    for name in dirs:        os.rmdir(os.path.join(root, name))

另一種方法

import shutilshutil.rmtree()

 

使用python刪除一個檔案或檔案夾

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.