Last active
March 10, 2020 14:22
-
-
Save ty4z2008/8cc548e8093029ac33a85bbf74985e0a to your computer and use it in GitHub Desktop.
读取filename.txt,对image目录下面的文件重命名
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
001 (1).jpg,111.jpg | |
001 (2).jpg,ddsg.jpg | |
001 (3).jpg,腊.jpg |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* filename.txt格式 | |
* 001 (1).jpg,111.jpg | |
* 001 (2).jpg,ddsg.jpg | |
* 001 (3).jpg,腊.jpg | |
* | |
**/ | |
package main | |
import ( | |
"bufio" | |
"bytes" | |
"fmt" | |
"io" | |
"os" | |
"strings" | |
) | |
var fileNameMap map[string]string | |
func readFileWithReadLine(fn string) (name map[string]string, err error) { | |
fmt.Println("readFileWithReadLine") | |
fileNameMap = make(map[string]string) | |
file, err := os.Open(fn) | |
defer file.Close() | |
if err != nil { | |
return fileNameMap, err | |
} | |
// Start reading from the file with a reader. | |
reader := bufio.NewReader(file) | |
for { | |
var buffer bytes.Buffer | |
var l []byte | |
var isPrefix bool | |
for { | |
l, isPrefix, err = reader.ReadLine() | |
buffer.Write(l) | |
// If we've reached the end of the line, stop reading. | |
if !isPrefix { | |
break | |
} | |
// If we're just at the EOF, break | |
if err != nil { | |
break | |
} | |
} | |
if err == io.EOF { | |
break | |
} | |
line := buffer.String() | |
nameStr := strings.Split(line, ",") | |
fileNameMap[nameStr[0]] = nameStr[1] | |
// Process the line here. | |
} | |
if err != io.EOF { | |
fmt.Printf(" > Failed!: %v\n", err) | |
} | |
return fileNameMap, nil | |
} | |
func rename(oldName string, newName string) { | |
err := os.Rename(oldName, newName) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
return | |
} | |
func main() { | |
filename, _ := readFileWithReadLine("./filename.txt") | |
const prefix string = "./image/" | |
for k, v := range filename { | |
rename(prefix+k, prefix+v) | |
} | |
fmt.Println("rename end") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment