用函数实现移动一个目录

import os

def move(src, dst):
    if os.path.abspath(src) == os.path.abspath(dst):
        print('地址相同,无法移动')
        return
    if os.path.isfile(src):
        src_fp = open(src, 'r')
        dst_fp = open(dst, 'w')
        while True:
            content = src_fp.read(1024)
            if len(content) == 0:
                break
            dst_fp.write(content)
        src_fp.close()
        dst_fp.close()
        # 删除源文件
        os.remove(src)
    else:
        if not os.path.exists(dst):
            os.makedirs(dst)
        dirs = os.listdir(src)
        for f in dirs:
            src_file = os.path.join(src, f)
            dst_file = os.path.join(dst, f)
            move(src_file, dst_file)
        # 删除原空目录
        os.rmdir(src)


# move('abc', 'test')
# move('00-test2.txt', '00-test.txt')

猜你喜欢

转载自blog.csdn.net/LoveL_T/article/details/81583547