Golang文件重命名

标签 go filenames

从昨天开始,我一直在尝试编写一个可以更改文件名的脚本/程序。除了学习 golang,我还开始制作动画,出于某种原因,Illustrator 将我制作的每个 .png 文件命名为这样 - “name_working space 1 copy.png”和“* copy (number).png”。我厌倦了手动重命名这些文件,今天我找到了这段代码并修改了其中的 1 行以删除“_working space 1 copy”,但仅限于那些有数字的文件。这给我留下了 2 个文件,它们是我的动画的第一帧,它们是 - “name_working space 1.png”; “名称_工作空间1副本.png”。我完全可以忍受将这两个留空,但由于我尝试学习 golang,我想问我是否可以改进它以替换每个文件名。我这周星期一开始学习。


import (
    "fmt"
    "log"
    "os"
    "path/filepath"
    "regexp"
)

func currentDir() {
    dir := "D:\\GoLang\\src\\gocourse\\renamefile\\rename"
    file, err := os.Open(dir)
    if err != nil {
        log.Fatalf("failed using this directory %s", err)
    }
    defer file.Close()

    list, err := file.Readdirnames(0)
    if err != nil {
        log.Fatalf("failed reading directory: %s", err)
    }

    re := regexp.MustCompile("_working space 1 copy ")
    for _, name := range list {
        oldName := name
        fmt.Println("Old name - ", oldName)
        newName := re.ReplaceAllString(oldName, "$1")
        fmt.Println("New Name - ", newName)
        err := os.Rename(filepath.Join(dir, oldName), filepath.Join(dir, newName))
        if err != nil {
            log.Printf("error renaming file: %s", err)
            continue
        }
        fmt.Println("File names have been changed")
    }
}

func main() {
    currentDir()
}
  • ball_working space 1.png --> ball-1.png;
  • ball_working space 1 copy.png --> ball-2.png;
  • ball_working space 1 副本 1.png --> ball-3.png;
  • ball_working space 1 copy 2.png --> ball-4.png 等

最佳答案

这是您的代码的重新实现。然而它并不完整,因为你需要 更好地阐明名称以前的样子以及它们应该是什么样子 之后。

package main

import (
   "os"
   "path/filepath"
   "strings"
)

func main() {
   dir := `D:\GoLang\src\gocourse\renamefile\rename`
   list, err := os.ReadDir(dir)
   if err != nil {
      panic(err)
   }
   for _, each := range list {
      name := each.Name()
      newName := strings.ReplaceAll(name, "_working space 1 copy", "")
      os.Rename(filepath.Join(dir, name), filepath.Join(dir, newName))
   }
}

关于Golang文件重命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66923776/

相关文章:

search - 批处理文件为: move files into a sub folder if they contain the filename of another file

去子串操作,没有索引越界?

go - 无效操作: (type interface {} does not support indexing)

java - 在Java中读取文件夹中的应用程序

c++ - 获取文件 : network or local 的位置

node.js - Node.js将目录中的文件名与文本文件中的文件名进行比较

json - 如何为一个端点创建多种验证方法?

go: regexp:FindAll() 中的 n 参数是什么

dictionary - map 中的最大元素数

Java按扩展名对文件名的String数组进行排序