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

2021-10-14 01:12:30 字數 1228 閱讀 5114

刪除檔案用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.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)

Python 模組學習 os模組

一 os模組概述 python os模組包含普遍的作業系統功能。如果你希望你的程式能夠與平台無關的話,這個模組是尤為重要的。一語中的 二 常用方法 1 os.name 輸出字串指示正在使用的平台。如果是window 則用 nt 表示,對於linux unix使用者,它是 posix 2 os.get...

Python 模組學習 os模組

一 os模組概述 python os模組包含普遍的作業系統功能。如果你希望你的程式能夠與平台無關的話,這個模組是尤為重要的。一語中的 二 常用方法 1 os.name 輸出字串指示正在使用的平台。如果是window 則用 nt 表示,對於linux unix使用者,它是 posix 2 os.get...

Python 模組學習 os模組

os模組提供了多個訪問作業系統服務的功能 os.name 顯示當前使用平台 os.getcwd 顯示當前python指令碼工作路徑 os.listdir dirname 顯示目錄dirname下的所有檔案和目錄名 os.remove filename 刪除乙個檔案 os.makedirs dirna...