溫馨提示×

python中如何實現rm命令的功能

小樊
120
2024-12-09 15:19:10
欄目: 編程語言

在Python中,你可以使用osshutil庫來實現類似于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_fileremove_directory。remove_file函數用于刪除一個文件,而remove_directory函數用于刪除一個目錄及其內容。在調用這些函數之前,我們首先檢查給定的路徑是否存在,如果存在,則使用os.remove()shutil.rmtree()進行刪除。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女