Untitled
user_2224127
golang
a year ago
2.5 kB
5
Indexable
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"strings"
)
// 获取目录下所有 .SEG 文件并按顺序重命名,同时修改文件内容的前三个字节
func renameAndModifyFiles(dir string) error {
// 读取目录中的所有文件
files, err := ioutil.ReadDir(dir)
if err != nil {
return fmt.Errorf("failed to read directory: %w", err)
}
// 用来存储所有的 .SEG 文件
var SEGFiles []string
// 遍历文件列表,找到所有的 .SEG 文件
for _, file := range files {
if !file.IsDir() && strings.HasSuffix(file.Name(), ".SEG") {
SEGFiles = append(SEGFiles, file.Name())
}
}
// 如果没有找到 .SEG 文件,返回
if len(SEGFiles) == 0 {
return fmt.Errorf("no .SEG files found in directory")
}
// 按文件名排序(如果需要按字母顺序排序,可以使用 sort.Strings 或其他排序方法)
sort.Strings(SEGFiles)
// 批量重命名文件并修改文件内容
for i, oldName := range SEGFiles {
// 生成新的文件名,格式为 001.SEG, 002.SEG 等
newName := fmt.Sprintf("%03d.SEG", i+1)
// 生成完整的文件路径
oldPath := filepath.Join(dir, oldName)
newPath := filepath.Join(dir, newName)
// 打开文件并修改前三个字节
err := modifyFileContent(oldPath, newPath, newName[:3])
if err != nil {
log.Printf("Error modifying file %s: %v", oldName, err)
continue
}
// 重命名文件
err = os.Rename(oldPath, newPath)
if err != nil {
log.Printf("Error renaming file %s to %s: %v", oldName, newName, err)
continue
}
fmt.Printf("Renamed and modified file: %s to %s\n", oldName, newName)
}
return nil
}
// 修改文件内容,将文件的前三个字节写为新的文件名中的三位数字
func modifyFileContent(oldPath, newPath, newFileName string) error {
// 打开文件
data, err := ioutil.ReadFile(oldPath)
if err != nil {
return fmt.Errorf("failed to read file %s: %w", oldPath, err)
}
// 修改文件的前三个字节
copy(data[:3], newFileName)
// 将修改后的数据写入新文件
err = ioutil.WriteFile(newPath, data, 0644)
if err != nil {
return fmt.Errorf("failed to write to file %s: %w", newPath, err)
}
return nil
}
func main() {
// 指定文件夹路径
dir := "./SEG_files" // 这里可以指定你要操作的目录
// 调用重命名并修改文件内容的函数
err := renameAndModifyFiles(dir)
if err != nil {
log.Fatalf("Error: %v", err)
}
}
Editor is loading...
Leave a Comment