package main
import (
"fmt"
"io/ioutil"
"os"
"path"
"strconv"
"strings"
)
func Rename(filepath string) {
files, err := ioutil.ReadDir(filepath)
if err != nil {
fmt.Println(err)
return
}
for _, file := range files {
if strings.Contains(file.Name(), "illust_") {
fmt.Println(file.Name())
newName := file.Name()[7:15] + "_p0" + path.Ext(file.Name())
_, err = os.Stat(filepath + "\\" + newName)
if err == nil { //同名文件在目录下已存在
for {
n := strings.Index(newName, "p")
index := newName[n+1]
i, _ := strconv.Atoi(string(index))
i += 1
newName = strings.Replace(newName, "_p"+string(index), "_p"+strconv.Itoa(i), 1)
_,err=os.Stat(filepath + "\\" + newName)
if err!=nil{
break
}
}
}
err = os.Rename(filepath+"\\"+file.Name(), filepath+"\\"+newName)
if err != nil {
fmt.Println(err)
}
}
}
}
func main() {
Rename("D:\\a")
}
go批量文件重命名
最新推荐文章于 2025-07-22 06:20:18 发布
本文介绍了一个使用Go语言编写的程序,该程序可以批量重命名指定路径下的文件。特别是对于包含特定字符串illust_的文件名进行处理,通过在文件名中间插入_p0并保留原有的文件扩展名来生成新的文件名。如果新文件名已存在,则程序会自动递增后缀中的数字直至找到未使用的名称。

566

被折叠的 条评论
为什么被折叠?



