1. 背景描述

最近在处理文件的时候,需要将文件根据TXT中的标签,进行分类整理至不同文件夹下。

具体情况是这样的。

首先在一个​​文件夹​​​下,有这样​​一系列的mp3文件​​:

├── music
├── test_00001.mp3
├── test_00002.mp3
├── test_00003.mp3
├── test_00004.mp3
├── ......
├── train_00001.mp3
├── train_00002.mp3
├── train_00003.mp3
├── train_00004.mp3
├── .......

然后,在一个​​TXT文件​​​中,对每个​​mp3文件​​​,都标注了文件​​类别​​:

test_00001.mp3 1
test_00002.mp3 3
test_00003.mp3 2
test_00004.mp3 3
....
train_00001.mp3 2
train_00002.mp3 3
train_00003.mp3 4
train_00004.mp3 1

其中​​第一列​​​就是对应​​文件的名字​​​,​​第二列​​​就是该文件所属的​​类别​​。

然后,还给出了​​不同类别​​​对应的分类的​​具体名称​​:

1: Classical
2: Rock
3: Symphony
4: Country

所以,主要目的就是实现将各个音乐文件,根据标签进行分类至不同文件夹。

同时,文件名带有​​test​​​的文件,要放在test文件夹下的分类中,带有​​train​​的文件,要放在train文件夹下的分类中。

最终我们想实现的结果是这样的:

├── music_split
├── test
├── Classical
├── test_00001.mp3
├── ......
├── Rock
├── test_00003.mp3
├── ......
├── Symphony
├── test_00002.mp3
├── test_00004.mp3
├── ......
└── Country
├── ......
└── train
├── Classical
├── train_00004.mp3
├── ......
├── Rock
├── train_00001.mp3
├── ......
├── Symphony
├── train_00002.mp3
├── ......
└── Country
├── train_00003.mp3
├── ......

接下来使用Python实现这个小小的功能。

2. 功能实现

详细源码如下:

import os
import shutil

# 读入分类的标签txt文件
label_file = open("E:\\【数据集】\\music\\list_label.txt", 'r')
# 原始文件的根目录
input_path = "E:\\【数据集】\\music\\music"
# 保存文件的根目录
output_path = "E:\\【数据集】\\music\\music_split"
# 标签数组
lables = ["Classical", "Rock", "Symphony", "Country"]

# 一行行读入标签文件
data = label_file.readlines()
# 计数用
i = 1
# 遍历数据
for line in data:
# 通过空格拆分成数组
str1 = line.split(" ")
# 第一个是文件名
file_name = str1[0]
# 第二个是标签类别,并去除最后的换行字符
file_label = str1[1].strip()
# 原始文件的路径
old_file_path = os.path.join(input_path, file_name)
# 新文件路径
new_file_path = ""

# 如果文件名中有test字符,将其保存至test文件夹下的对应标签文件夹中
if "test" in file_name:
new_file_path = os.path.join(output_path, "test", lables[int(file_label) - 1])
# 如果文件名中有 train 字符,将其保存至train文件夹下的对应标签文件夹中
elif "train" in file_name:
new_file_path = os.path.join(output_path, "train", lables[int(file_label) - 1])

# 如果路径不存在,则创建
if not os.path.exists(new_file_path):
print("路径 " + new_file_path + " 不存在,正在创建......")
os.makedirs(new_file_path)

# 新文件位置
new_file_path = os.path.join(new_file_path, file_name)
print("" + str(i) + "\t正在将 " + old_file_path + " 复制到 " + new_file_path)
# 复制文件
shutil.copyfile(old_file_path, new_file_path)

i = i + 1
# 完成提示
print("完成")

源码中已经给出了详细的注释。