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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程