dongtao4319 2018-01-11 11:47
浏览 87
已采纳

无法在go中使用filepath.Walk()重命名给定路径中的所有目录

This is my visit function,

func visit(path string, f os.FileInfo, err error) error {
    if !f.IsDir() {
        return nil
    }
    str := path
    if str == config.Path {
        return nil
    }
    if str == config.LatestPath {
        return nil
    }
    dir := str
    dir = strings.TrimPrefix(str, filepath.Dir("C:\\Users\\Mark\\Desktop\\testfolder\\"))
    slashes := strings.Count(dir, "\\")
    if slashes < config.PrevSlashes {
        x := len(config.Slashes) - 1
        for x > slashes {
            config.Slashes[x] = 0
            x--
        }
    }
    config.Slashes[slashes]++
    config.PrevSlashes = slashes
    prename := ""
    for k, v := range config.Slashes {
        if k != 0 {
            if k <= slashes {
                prename += strconv.Itoa(v) + "."
            }
        }
    }
    fmt.Println(config.Slashes)
    myRegex := `(\\(?P<number>[\d\.]*))  \w`
    for i := 0; i < slashes-1; i++ {
        myRegex += `(\\(?P<number` + strconv.Itoa(i) + `>[\d\.]*))  \w*`
    }
    re := regexp.MustCompile(myRegex)
    for i, match := range re.FindAllString(dir, -1) {
        return nil
        fmt.Println(i, match)
    }
    Cdir := filepath.Dir(path)
    newpath := fmt.Sprintf("%s\\%s  %s", Cdir, prename, f.Name())
    config.LatestPath = path
    os.Rename(path, newpath)
    return nil
}

the folder structure looks like this

testfolder\a\aa\aaa, 
testfolder\a\aa\aab, 
testfolder\a\aa\aac, 
testfolder\a\ab\aaa

The problem that i have is filepath,Walk() does not see the changed directory names.

it first renames testfolder\a\aa\aaa to testfolder\1. a\aa\aaa and then it tries to rename testfolder\a\aa\aaa to testfolder\a\1. aa\aaa but i want it to rename testfolder\1. a\aa\aaa to testfolder\1. a\1.1. aa\aaa

the end result should look like

\testfolder\1. a\1.1. aa\1.1.1. aaa
\testfolder\1. a\1.1. aa\1.1.2. aab
\testfolder\1. a\1.1. aa\1.1.3. aac
\testfolder\1. a\1.2. ab\1.2.1. aaa
\testfolder\1. a\1.2. ab\1.2.2. aab
\testfolder\2. b\2.1. aa\2.1.1. aaa
\testfolder\2. b\2.1. aa\2.2.2. aab

simply said i want to name a directory "x. name" and the folders in it "x.x. name" where x is a number

EDIT 1 : i worked around the problem by calculating the path names and putting those in an array and then renaming the directories after the filepath.Walk() function has finished

func visit(path string, f os.FileInfo, err error) (error) {
if err != nil {
    log.Fatal(err)
}
if !f.IsDir() {
    return nil
}
str := path
if str == config.Path {
    return nil
}
dir := str
dir = strings.TrimPrefix(str, filepath.Dir("C:\\Users\\Mark\\Desktop\\testfolder\\"))
slashes := strings.Count(dir, "\\")
if slashes < config.PrevSlashes {
    x := len(config.Slashes) - 1
    for x > slashes {
        config.Slashes[x] = 0
        x--
    }
}
config.Slashes[slashes]++
config.PrevSlashes = slashes
prename := ""
for k, v := range config.Slashes {
    if k != 0 {
        if k <= slashes {
            prename += strconv.Itoa(v) + "."
        }
    }
}
myRegex := `(\\(?P<number>[\d\.]*))  \w`
for i := 0; i < slashes-1; i++ {
    myRegex += `(\\(?P<number` + strconv.Itoa(i) + `>[\d\.]*))  \w*`
}
re := regexp.MustCompile(myRegex)
for i, match := range re.FindAllString(dir, -1) {
    config.Dirpaths[slashes] = fmt.Sprintf("%s", f.Name())
    return nil
    fmt.Println(i, match)
}
config.Dirpaths[slashes] = fmt.Sprintf("%s  %s", prename, f.Name())
prenameOld := ""
for k, v := range config.Dirpaths {
    if k != 0 {
        if v != "" {
            if k == slashes {
                break
            }
            prenameOld += v + "\\"
        }
    }
}
oldname := strings.TrimRight(config.Path+prenameOld+f.Name(), "\\")
newName := strings.TrimRight(config.Path+prenameOld+config.Dirpaths[slashes], "\\")
if len(config.OldNames) != config.MaxDir {
    config.OldNames = append(config.OldNames, oldname)
    config.NewNames = append(config.NewNames, newName)
}
return nil
}
  • 写回答

1条回答 默认 最新

  • drblhw5731 2018-01-11 12:15
    关注

    If you look at the source for filepath.Walk, you'll see that it does the following:

    • get sorted listed of names for the current directory
    • for each name:
      • call your callback function
      • call walk(name)

    With your given directories, the first call inside testfolder will be for testfolder/a since testfolder/1 does not yet exist.

    No matter what you do, Walk will not reread testfolder/, so it will never see the new 1. a subdirectory.

    Renaming dirs/files during Walk is a great way to get the wrong behavior. Instead, I would recommend you list files in the directories yourself and do your own recursion.

    Something along the lines of:

    • pick next dir to process (by default, testfolder)
    • read current subdirectories/files of dir using File.ReadDirNames
    • for each entry:
      • rename as needed
      • add new name to list of directories to process

    This uses iteration. Alternatively, you can recurse on the new name (this is where filepath.Walk fails you as it doesn't know about the new name).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?