如何重命名Golang中不同目录中的一组文件

时间:2018-04-23 01:43:35

标签: python-2.7 go

我在Python 2.7中创建了一个程序,它通过替换这些文件名中的数字来重命名目录中的文件。我尝试使用Golang应用程序做同样的事情,但它无法正常工作。控制台仍然提供新名称,但它不会更改文件目录中的照片名称。

这是python程序

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()

这很好用。但是,这个Golang脚本没有 这是Golang计划

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()

}

如果你想从github repo中将它们提取到项目,这里有一个链接,它将为你提供存储图像的代码和照片文件夹。通过查看我的代码需要更改的位置,我将受益最多。您将给予的任何帮助或建议将不胜感激。非常感谢你。

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

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

1 个答案:

答案 0 :(得分:3)

在Go中,始终始终检查错误。你的许多问题都会很明显。例如,您有os.Rename个错误。

使用filepath包来操作文件名路径。编译常量regex表达式只应该执行一次。修复您的regexp错误:"[^A-za-z]"应为"[^A-Za-z]"

这是一个有效的版本:

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()
}

输出:

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

差异:

> 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()
-
 }
>