前六位一样的文件放在一个新建文件夹中,文件夹命名为刚才的前六位

前六位一样的txt文件放在同一个新建文件夹里,文件夹命名为这个前六位,想问一下怎么实现?

files = os.listdir(source_path)
for file in files:
    shutil.copy('原始路径/' + file, "目标根路径/" + file[0:6] + '/' + file[7: ])

import os
import shutil

 
def move_file(file_path):
    """将文件移动到指定文件夹"""
    if not os.path.exists(file_path):
        print ("%s not exist!"%(file_path))
        return
    file_list = os.listdir(file_path)
    for file in file_list:
        # 判断是否是txt文件
        if not file.endswith('.txt'):
            continue
        dstpath = os.path.join(file_path, file[:6])
        # 判断文件夹是否存在
        if not os.path.exists(dstpath):
            os.makedirs(dstpath)
        # 创建路径
        shutil.move(file, os.path.join(dstpath, file))          # 移动文件
        print ("move %s -> %s" % (file, os.path.join(dstpath, file)))
 
move_file(r'/test/')

有帮助的话,请点采纳该答案~