1. 程式人生 > 其它 >Python學習:os模組刪除檔案、資料夾

Python學習:os模組刪除檔案、資料夾

技術標籤:Pythonpythonos

刪除檔案/資料夾

刪除檔案,os.remove方法

刪除檔案用python的內建模組os的os.remove方法
關於os.path.join()方法請參見文章Python學習:開啟資料夾中的所有txt檔案

os.remove(檔案路徑) 刪除檔案

import os
# 檔案所在目錄
path="D:\pythonProject"
# 檔名字
txt_name0="刪除檔案0.txt"
# os.path.join(path,txt_name0) 獲得檔案所在路徑,並用 os.remove(檔案路徑) 刪除
os.remove(os.path.join(path,txt_name0))

刪除資料夾

  • 刪除資料夾用os.rmdir(資料夾路徑)
  • 刪除資料夾不能用 os.remove(資料夾路徑),否則會報錯:[WinError 5] 拒絕訪問。: ‘資料夾路徑’
  • 刪除的資料夾必須為空,否則報錯:[WinError 145] 目錄不是空的。: ‘資料夾路徑’

os.listdir()用法見文章Python學習:開啟資料夾中的所有txt檔案

try execpt用於丟擲異常,用法待更新

import os

path="D:\pythonProject"

dic_name="刪除資料夾"
dic_path=os.path.join(path,dic_name) # 用os.remove()刪除資料夾報錯 try: os.remove(dic_path) except Exception as result: print("報錯1:%s"% result) # 用os.rmdir()刪除非空資料夾報錯 try: os.rmdir(dic_path) except Exception as result: print("報錯2:%s"%result) # 先刪除資料夾中的檔案,再刪除空資料夾 try: # for 迴圈刪除資料夾中的檔案
for i in os.listdir(dic_path): # print(i) txt_path=os.path.join(dic_path,i) os.remove(txt_path) os.rmdir(dic_path) except Exception as result: print("報錯3:%s"%result)