昨天在ping多多上买周杰伦的所用mp3歌曲,店家过来的网盘资源,文件名称全部都是有空格或者数字
三百首歌曲,总不会一个个改吧
好在之前学了python还没全忘,写了个遍历该目录所有的所有目录和文件,并且使用正则修改名称
from os.path import isfile, isdir
from os import listdir
import os
import re
##查询文件夹的文件
def traverseDir(path):
for mulu in listdir(path): #返回path目录下的文件和目录列表
subpath = path + "\\" + mulu
if isfile(subpath): #判断是否是文件
#旧目录路径subpath
#目录名称修改
newmulu = re.sub(r"(\d+.)|(\s+)",'',mulu)
#newmulu = '周杰伦 - '+mulu
newpath = path + "\\" + newmulu
os.rename(subpath,newpath)
elif isdir(subpath): #判断是否是文件夹
#旧目录路径subpath
#目录名称修改
newmulu = re.sub(r"(\d+.)|(\s+)",'',mulu)
#print(newmulu)
newpath = path + "\\" + newmulu
os.rename(subpath,newpath)
traverseDir(subpath) #深度搜索
traverseDir("C:\\Users\\user\\Desktop\\downloadFile\\baiduPan\\周杰伦全集 MP3")
print("成功")
js代码修改
const fs = require('fs');
const path = require('path');
const cnchars = require('cn-chars');//需要安装
//
function traveserDir(filepath) {
//获取该路径下的子文件名或者目录名
fs.readdir(filepath, function (err, files) {
if (err) {
throw err;
}
//便利名称数组
files.forEach(function (item, index) {
//该文件or目录路径
let subpath = path.join(filepath, item);
//读取文件的状态
fs.stat(subpath, (err, stats) => {
if (err) throw err;
//判断是否为文件
if (stats.isFile() === true) {
//修改名称
// let newName = item.replace('要替换的字符', '替换成字符');
let notTranNewName = item;
//繁体转简体
let newName = "";
for(let char of notTranNewName){
newName = newName + cnchars.toSimplifiedChar(char);
}
//拼接路径
let newPath = path.join(filepath, newName);
//写入
fs.rename(subpath, newPath, (err) => {
if (err) throw err;
console.log(item + '-->' + newName);
});
}
//判断是否为目录
else if (stats.isDirectory() === true) {
//深度查找
traveserDir(subpath);
}
});
})
});
}
traveserDir(path.join(__dirname, "相对路径"));