Python之os模块

os是个常用的模块,必须熟练。

# python3
# coding = utf-8

import os
import shutil

# 大小以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')

 

参考资料:

https://docs.python.org/3/library/os.html

How do I remove/delete a folder that is not empty with Python?

posted @ 2017-07-31 20:46  Sawyer Ford  阅读(156)  评论(0编辑  收藏  举报