在Python中,你可以使用os
和shutil
庫來實現類似于rm
命令的功能
import os
import shutil
def remove_file(file_path):
if os.path.exists(file_path):
os.remove(file_path)
print(f"{file_path} 已被刪除")
else:
print(f"{file_path} 不存在")
def remove_directory(dir_path):
if os.path.exists(dir_path):
shutil.rmtree(dir_path)
print(f"{dir_path} 已被刪除")
else:
print(f"{dir_path} 不存在")
file_to_delete = "example.txt"
dir_to_delete = "example_directory"
remove_file(file_to_delete)
remove_directory(dir_to_delete)
在這個示例中,我們定義了兩個函數:remove_file
和remove_directory
。remove_file
函數用于刪除一個文件,而remove_directory
函數用于刪除一個目錄及其內容。在調用這些函數之前,我們首先檢查給定的路徑是否存在,如果存在,則使用os.remove()
或shutil.rmtree()
進行刪除。