Python puts the files in the folder into different folders according to the extension

Purpose: There are many files in a folder, and there are many kinds of extensions, it is very troublesome to copy and paste manually, I want to use code to achieve.
Create a new folder with some files for testing: The
Insert picture description herecode implements a new folder based on the extension, and puts all files with the same extension under this folder:

import shutil
import os
def classify(filespath,outpath):
    files=os.listdir(filespath)  # 获取所有的文件
    for x in files:
        srcname=os.path.join(filespath,x)  #每个文件的完整路径
        houzhui=x.split(".")[-1]  # 获取后缀名
        outfiles=os.path.join(outpath,houzhui) # 要放入的文件夹的路径
        if not os.path.exists(outfiles): # 路径不存在则创建
            os.mkdir(outfiles)
        filename=outfiles+"\\"+x
        print("复制文件---{}到--{}".format(srcname,filename))
        shutil.copyfile(srcname,filename)  # 复制文件


if __name__=='__main__':
    filespath = "E:/program/python/test"  # 存放文件的文件夹路径
    outpath = "E:/program/python/ffoutput" # 分类后的文件夹路径
    classify(filespath,outpath)

The code is mainly the shutil.copyfile(src,dst) module:

def copyfile(src, dst, *, follow_symlinks=True):
    """Copy data from src to dst.

    If follow_symlinks is not set and src is a symbolic link, a new
    symlink will be created instead of copying the file it points to.

    """

src and dst must be files, not directories. If dst already exists, it will be overwritten.

Guess you like

Origin blog.csdn.net/liulanba/article/details/110873457