os is a commonly used module and must be proficient.
# python3 # coding = utf-8 import os import shutil #size in M def get_dir_size(dir_path): dir_size = 0 for root, dirs, files in os.walk(dir_path): for name in files: dir_size += os.path.getsize(os.path.join(root, name)) return dir_size / (1024 ** 2) def delete_dir_recursively(dir_path): if os.path.isdir(dir_path): shutil.rmtree(dir_path) else: print(dir_path, 'not exist') def delete_dir_recursively2(dir_path): for root, dirs, files in os.walk(dir_path, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) print('dir size:', get_dir_size('/root/dev/shell')) dir_content = os.listdir('/root/dev/shell') print('dir content:', dir_content) # join 用法 dir_str = ' ## ' .join (dir_content) print ( ' dir_str: ' , dir_str) delete_dir_recursively('/root/dev/shell_bck1') delete_dir_recursively2('/root/dev/shell_bck2')
References:
https://docs.python.org/3/library/os.html
How do I remove/delete a folder that is not empty with Python?
Reprinted in: https://www.cnblogs.com/gattaca/p/7265619.html