doujing5937 2018-04-23 01:43
浏览 117

如何在Golang中的其他目录中重命名一组文件

I made a program in Python 2.7 that renames the files in a directory by replacing the numbers in those file names. I tried to do the same thing with a Golang app but it is not working. The console still gives be new names but it is not changing the names of the photos in the file directory.

Here is the python program

import os
def rename_files():
    #(1) get files names from a folder
    file_list = os.listdir(r"C:\\Users\\g\\Desktop\\Fun\\udacity\\foundationsofpython\\07finalrenamingapp\\prank")
    print(file_list)
    saved_path = os.getcwd()
    print (saved_path)
    os.chdir(r"C:\\Users\\g\\Desktop\\Fun\\udacity\\foundationsofpython\\07finalrenamingapp\\prank")

    #2 rename all files names in folder
    for file_name in file_list:
        print ("Old Name - " +file_name)
        print ("New Name - " +file_name.strip("0123456789"))
        os.rename(file_name,file_name.strip("0123456789"))
    os.chdir(saved_path)

rename_files()

This works just fine. However, this Golang script does not This is the Golang program

package main

import (
    "log"
    "os"
    "fmt"
    "regexp"
)
func readCurrentDir() {
    dir := "C:\\Users\\g\\Desktop\\prank"
    file, err := os.Open(dir)
    if err != nil {
        log.Fatalf("failed opening directory: %s", err)
    }
    defer file.Close()

    list,_ := file.Readdirnames(0) // 0 to read all files and folders
    for _, name := range list {
        oldName := name
        fmt.Println("Old Name - ", oldName)
        re := regexp.MustCompile( "[^A-za-z]" )
        newName := re.ReplaceAllString( oldName, " ")
        fmt.Println("New Name - ", newName)        
        os.Rename(dir+oldName, dir+newName)
        fmt.Println("File names have been changed")

    }
}

func main() {
    readCurrentDir()

}

If you want to pull these to projects from the github repo here is a link that will provide you with the code and the photo folder where the images are stored. I would benefit the most by seeing where my code needs to be changed. Any help or advice you could give would be greatly appreciated. Thank you very much.

Python App https://github.com/lashleykeith/GoingwithGolang/tree/master/OldCode2BeChanged

Golang App https://github.com/lashleykeith/GoingwithGolang/tree/master/our_tutorial/5finalrenamingapp

  • 写回答

1条回答 默认 最新

  • duanhe6718 2018-04-23 03:31
    关注

    In Go, always, always, check for errors. Many of your problems will then be obvious. For example, you have os.Rename errors.

    Use the filepath package to manipulate filename paths. Compiling a constant regex expression should only be done once. Fix your regexp bug: "[^A-za-z]" should be "[^A-Za-z]".

    Here's a working version:

    package main
    
    import (
        "fmt"
        "log"
        "os"
        "path/filepath"
        "regexp"
    )
    
    func readCurrentDir() {
        dir := "C:\\Users\\g\\Desktop\\prank"
        file, err := os.Open(dir)
        if err != nil {
            log.Fatalf("failed opening directory: %s", err)
        }
        defer file.Close()
    
        list, err := file.Readdirnames(0) // 0 to read all files and folders
        if err != nil {
            log.Fatalf("failed reading directory: %s", err)
        }
        re := regexp.MustCompile("[^A-Za-z]")
        for _, name := range list {
            oldName := name
            fmt.Println("Old Name - ", oldName)
            newName := re.ReplaceAllString(oldName, " ")
            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() {
        readCurrentDir()
    }
    

    Output:

    Old Name -  prankster.42.txt
    New Name -  prankster    txt
    File names have been changed
    

    Diff:

    > git diff old.go new.go
    diff --git a/old.go b/new.go
    index 464b60e..7ae276e 100644
    --- a/old.go
    +++ b/new.go
    @@ -4,6 +4,7 @@ import (
            "fmt"
            "log"
            "os"
    +       "path/filepath"
            "regexp"
     )
    
    @@ -15,69 +16,31 @@ func readCurrentDir() {
            }
            defer file.Close()
    
    -       list, _ := file.Readdirnames(0) // 0 to read all files and folders
    +       list, err := file.Readdirnames(0) // 0 to read all files and folders
    +       if err != nil {
    +               log.Fatalf("failed reading directory: %s", err)
    +       }
    +       re := regexp.MustCompile("[^A-Za-z]")
            for _, name := range list {
                    oldName := name
                    fmt.Println("Old Name - ", oldName)
    -               re := regexp.MustCompile("[^A-za-z]")
                    newName := re.ReplaceAllString(oldName, " ")
                    fmt.Println("New Name - ", newName)
    -               os.Rename(dir+oldName, dir+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() {
            readCurrentDir()
    -
     }
    >
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题