如何根据文件名将多个文件从一个文件夹中分离到单独的文件夹中?

How can I separate many files from one folder into separate folders based on the name of the files?

当前的文件组织是这样的:

Species_name1.asc
Species_name1.csv
Species_name1_Averages.csv
...
...
Species_name2.asc
Species_name2.csv
Species_name2_Averages.csv

我需要找出一个脚本,它可以创建名称为(Species_name1、Species_name2...等)的新目录,并且可以将文件从基目录移动到适当的新目录。

import os
import glob
import shutil

base_directory = [CURRENT_WORKING_DIRECTORY]

with open("folder_names.txt", "r") as new_folders:
     for i in new_folders:
          os.mkdirs(base_directory+i)

以上是我在基本目录中创建新目录时可以想到的示例。

我知道如果我要使用 python,我将不得不使用 os、shutil、and/or glob 模块中的工具。然而,确切的脚本正在逃避我,我的文件仍然杂乱无章。如果您有任何建议可以帮助我完成这个小任务,我将不胜感激os。

此目录中还有许多文件类型和后缀,但 (species_name?) 部分始终保持一致。

以下是预期的层次结构:

Species_name1
-- Species_name1.asc
-- Species_name1.csv
-- Species_name1_Averages.csv
Species_name2
-- Species_name2.asc
-- Species_name2.csv
-- Species_name2_Averages.csv

提前致谢!

像这样使用简单的 shell 工具 :

find . -type f -name '*Species_name*' -exec bash -c '
    dir=$(grep -oP "Species_name\d+" <<< "")
    echo mkdir "$dir"
    echo mv "" "$dir"
' -- {} \; 

当输出看起来不错时,删除 echo 命令。

假设您所有的 asc 文件都按照您的示例命名:

from os import  mkdir
from shutil import move
from glob import glob

fs = []
for file in glob("*.asc"):
    f = file.split('.')[0]
    fs.append(f)
    mkdir(f)
    
for f in fs:
    for file in glob("*.*"):
        if file.startswith(f):
            move(file, f'.\{f}\{file}')


更新:

假设您所有的 Species_name.asc 文件都像示例中那样被标记:

from os import  mkdir
from shutil import move
from glob import glob

fs = [file.split('.')[0] for file in glob("Species_name*.asc")]
    
for f in fs:
    mkdir(f)
    for file in glob("*.*"):
        if file.startswith(f):
            move(file, f'.\{f}\{file}')