python3 递归遍历文件夹,把所有散落的文件移到一个文件夹里

费话少说
show code

#!/usr/bin/env python3
# coding:utf-8

import os
import shutil

#判断输出的文件夹是否存在
def outpathfolder(outpath):
    if not os.path.exists(outpath):
        os.makedirs(outpath)

#主程序,使用递归,函数嵌套
def getfilepath(path):
    allpiclist = os.listdir(path)
    for i in allpiclist:
        filepath = os.path.join(path,i)
        # print(filepath)
        if os.path.isdir(filepath):
            getfilepath(filepath) #递归
        else:
            shutil.copy2(filepath,outpath)

if  __name__ == '__main__':
    path = "p" #需要遍历的文件夹****** 重要 *******
    outpath = "out" #输出的文件夹
    outpathfolder(outpath) #如果不存在这个文件夹则创建一个
    getfilepath(path)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。