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

当前文件组织如下所示:


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 和/或 glob 模块中的工具。然而,确切的脚本正在逃避我,我的文件仍然杂乱无章。如果您有任何建议可以帮助我完成这个小任务,我将不胜感激。


此目录中还有许多文件类型和后缀,但 (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


先感谢您!


aluckdog
浏览 137回答 2
2回答

阿波罗的战车

像这样使用简单的 shell 工具狂欢:find . -type f -name '*Species_name*' -exec bash -c '&nbsp; &nbsp; dir=$(grep -oP "Species_name\d+" <<< "$1")&nbsp; &nbsp; echo mkdir "$dir"&nbsp; &nbsp; echo mv "$1" "$dir"' -- {} \;&nbsp;echo 当输出看起来不错时删除命令。

吃鸡游戏

假设您的所有asc文件都像示例中那样命名:from os import&nbsp; mkdirfrom shutil import movefrom glob import globfs = []for file in glob("*.asc"):&nbsp; &nbsp; f = file.split('.')[0]&nbsp; &nbsp; fs.append(f)&nbsp; &nbsp; mkdir(f)&nbsp; &nbsp;&nbsp;for f in fs:&nbsp; &nbsp; for file in glob("*.*"):&nbsp; &nbsp; &nbsp; &nbsp; if file.startswith(f):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; move(file, f'.\\{f}\\{file}')更新:假设您的所有Species_name.asc文件都像您的示例中那样标记:from os import&nbsp; mkdirfrom shutil import movefrom glob import globfs = [file.split('.')[0] for file in glob("Species_name*.asc")]&nbsp; &nbsp;&nbsp;for f in fs:&nbsp; &nbsp; mkdir(f)&nbsp; &nbsp; for file in glob("*.*"):&nbsp; &nbsp; &nbsp; &nbsp; if file.startswith(f):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; move(file, f'.\\{f}\\{file}')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python