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

无法在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).

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题