用Python将多个文件夹中的文件移至根目录

因某些业务需求,需要移动大量文件到根目录。
这里分循环和递归两种实现方式
1. 覆盖掉同名文件的实现方式

all_dirs = []
all_files = []
path = os.getcwd()
list_files = os.walk(path)
for dirpath,dirnames,filenames in list_files:
    for dir in dirnames:
        all_dirs.append(os.path.join(dirpath,dir))
    for file in filenames:
        all_files.append(os.path.join(dirpath,file))
        abs_file = os.path.join(dirpath,file)
        try:
           shutil.move(abs_file,path+"\\"+file)
           print("move : " + file)
           pass
        except Exception as e:
            print(e)
# 删除文件夹
# for dir in all_dirs:
#     try: shutil.rmtree(dir)
#     except Exception as e:
#         print(e)
print("done")

2.递归实现并保留重复文件

# coding=utf-8
import shutil
import os


def move(src,dst):
    ls = os.listdir(os.path.pardir)
    dst_2 = dst.split('\\')
    if dst_2[-1] in ls and os.path.getsize(dst) != os.path.getsize(src):
        dst = dst[0:-4] + '-' + dst[-4:-1] + dst[-1]
        move(src,dst)
        return
    print("MOVE : "+src+" TO "+dst,file=history)
    shutil.move(src,dst)
    
def move_file(file_list,depth):
    for file in file_list:
        if os.path.isdir(file):
            os.chdir(file)
            ls = os.listdir()
            move_file(ls,depth+1)
            os.chdir(os.path.pardir)
        else:
            # for i in range(depth):
            #     print(" - ",end="")
            # print(file)
            move(os.path.join(os.getcwd(),file),os.path.join(parent_dir,file))
    pass

history = open('history.txt','a+')
cwd = os.listdir()
parent_dir = os.getcwd()
cwd_2 = []
for folder in cwd:
    if os.path.isdir(folder):
        cwd_2.append(folder)

move_file(cwd_2,0)
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北極企鹅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值