dongyishen5796 2013-11-21 07:56
浏览 2383
已采纳

Golang:重命名目录和部分文件重命名?

Go has this package and function

package main

import "os"

func main() {
  os.Rename("LICENSE", "e")
}

This changes the filename LICENSE to e.

But what I want to do is the following and can't find how to do it. Ruby does this so should Go. Where should I look up?

  1. Change the name of directory not files....

  2. Rename just the part of the name. For example, if I have a file or directory "Example", I would want to change "Exa" to "Stq," then the word would be "Stqmple"

What package should I use?

Thanks in advance.

  • 写回答

2条回答 默认 最新

  • dsdvr06648 2013-11-21 16:30
    关注
    1. os.Rename will work fine on directories, including windows. The only bit to question here is whether the operation is atomic, which on all major platforms the answer is yes.

    2. If you want to locate files and directories that match a pattern, you'll want to look at the filepath package. This will let you traverse a directory at which point you can inspect each file and match the name against your requirements. Look at func Walk and type WalkFn of the documentation. http://golang.org/pkg/path/filepath/#Walk

    Here's an example of using Walk to locate png files in a given directory or any of its subdirectories:

    package main
    
    import (
        "flag"
        "fmt"
        "os"
        "path/filepath"
    )
    
    var flagPath = flag.String("path", "", "recursively traverse path and print png filepaths to stdout.")
    
    func visit(path string, f os.FileInfo, err error) error {
        if filepath.Ext(path) == ".png" {
            fmt.Println(path)
        }
        return nil
    }
    
    func main() {
        flag.Parse()
        if *flagPath == "" {
            flag.Usage()
            return
        }
        filepath.Walk(*flagPath, visit)
    }
    

    Here's a func visit that does what your asking about in the comment, be sure to import "strings":

    func visit(path string, f os.FileInfo, err error) error {
        if name := f.Name(); strings.HasPrefix(name, "name_") {
            dir := filepath.Dir(path)
            newname := strings.Replace(name, "name_", "name1_", 1)
            newpath := filepath.Join(dir, newname)
            fmt.Printf("mv %q %q
    ", path, newpath)
            os.Rename(path, newpath)
        }
        return nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?