一、跨平台操作
shutil模塊是Python自帶的一個高級文件操作工具,其中,shutil.rmtree(path, ignore_errors=False, onerror=None)方法可以刪除一個目錄及其子目錄和文件,其可以跨平台操作,適用於Windows,Linux,Mac OS等操作系統,因此在開發跨平台應用時非常有用。
import os
import shutil
dir_path = "test_dir"
os.makedirs(dir_path)
file_path = "test_file.txt"
with open(file_path, "w") as f:
f.write("hello world")
shutil.rmtree(dir_path)
os.remove(file_path)
上述代碼示例中創建了一個test_dir目錄和一個test_file.txt文件,最後通過shutil.rmtree和os.remove方法分別刪除了目錄和文件,該代碼在Windows,Linux,Mac OS系統下均可運行。
二、避免誤刪除
shutil.rmtree方法刪除目錄時,如果未傳入ignore_errors=True參數,它會在目錄不存在或者打開目錄失敗時拋出異常,這有助於避免誤刪除問題。
import os
import shutil
dir_path = "test_dir"
os.makedirs(dir_path)
# 刪除不存在的目錄
try:
shutil.rmtree("test")
except Exception as e:
print(e)
# 刪除目錄失敗
try:
os.chdir(dir_path)
shutil.rmtree("..")
except Exception as e:
print(e)
shutil.rmtree(dir_path, ignore_errors=True)
上述代碼示例中首先創建了一個test_dir目錄,之後嘗試刪除不存在的test目錄和存在但是打開失敗的test_dir上級目錄,最後通過ignore_errors=True參數刪除了test_dir目錄。
三、刪除只讀文件
在Windows系統下,文件屬性可能會被設置為只讀,此時我們無法直接刪除該文件。不過shutil模塊提供了chattr方法用於修改文件屬性,從而實現刪除文件的功能。
import os
import shutil
# 創建只讀文件
file_path = "test.txt"
with open(file_path, "w") as f:
f.write("hello world")
os.chmod(file_path, 0o440)
# 刪除只讀文件
os.chmod(file_path, 0o777)
os.remove(file_path)
上述代碼示例中首先創建了一個只讀文件test.txt,之後通過os.chmod方法修改文件許可權為0o777,從而實現刪除文件的功能。
四、刪除文件夾下指定類型文件
在操作文件夾時,有時候我們只需要刪除文件夾下指定類型的文件,可以通過遍歷文件夾並篩選出指定類型文件的方式實現此功能。
import os
import shutil
dir_path = "test_dir"
os.makedirs(dir_path)
file1_path = os.path.join(dir_path, "test1.txt")
with open(file1_path, "w") as f:
f.write("hello world")
file2_path = os.path.join(dir_path, "test2.txt")
with open(file2_path, "w") as f:
f.write("hello world")
file3_path = os.path.join(dir_path, "test3.md")
with open(file3_path, "w") as f:
f.write("hello world")
for root, dirs, files in os.walk(dir_path):
for name in files:
if name.endswith(".txt"):
os.remove(os.path.join(root, name))
shutil.rmtree(dir_path)
上述代碼示例中創建了一個test_dir目錄,其中包含了三個不同類型的文件,之後通過os.walk沿著目錄樹遍歷文件夾,通過name.endswith(“.txt”)篩選出指定類型的文件並刪除。
五、安全刪除文件
在刪除文件時,有時候為防止誤刪除,我們需要在刪除前先備份文件再刪除,此時可以使用shutil.move實現文件的備份和刪除。
import os
import shutil
file_path = "test.txt"
with open(file_path, "w") as f:
f.write("hello world")
backup_path = shutil.move(file_path, file_path + ".bak")
os.remove(backup_path)
上述代碼示例中首先創建了一個test.txt文件,之後使用shutil.move方法將該文件備份為test.txt.bak,最後刪除備份文件test.txt.bak。
六、解決Windows文件夾路徑斜杠問題
在Windows系統下,文件夾路徑使用「\\」斜桿作為分隔符,在Linux和Mac OS系統下則使用「/」斜桿作為分隔符,可以使用os.path.join方法解決跨平台路徑問題。
import os
import shutil
dir_path = os.path.join("test_dir", "sub_dir")
os.makedirs(dir_path)
file_path = os.path.join(dir_path, "test.txt")
with open(file_path, "w") as f:
f.write("hello world")
shutil.rmtree(dir_path)
上述代碼示例中使用os.path.join方法生成跨平台路徑,確保在不同系統下依然可以正確創建文件。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/300857.html