栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用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)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/269254.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号