以下为示例代码:
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
)
func main() {
downloadsDir := "C:\\Users\\You\\Downloads"
csvFiles, err := filepath.Glob(filepath.Join(downloadsDir, "*.csv"))
if err != nil {
fmt.Println("Error finding CSV files:", err)
return
}
for _, csvFile := range csvFiles {
fileInfo, err := os.Stat(csvFile)
if err != nil {
fmt.Println("Error getting file info:", err)
continue
}
if fileInfo.ModTime().Day() != time.Now().Day() {
continue // skip file if not created today
}
fmt.Println("Processing CSV file:", csvFile)
fileBytes, err := ioutil.ReadFile(csvFile)
if err != nil {
fmt.Println("Error reading file:", err)
continue
}
if !strings.Contains(string(fileBytes), "是否留痕的位置") {
continue // skip file if header not found
}
// convert file to UTF-8 encoding
fileBytes, err = decodeToUTF8(fileBytes)
if err != nil {
fmt.Println("Error decoding file to UTF-8:", err)
continue
}
// do something with file content here
fmt.Println("File content:", string(fileBytes))
}
}
func decodeToUTF8(fileBytes []byte) ([]byte, error) {
// detect source encoding
encoding, _, _ := charset.DetermineEncoding(fileBytes, "")
// if already UTF-8, return as is
if encoding == unicode.UTF8 {
return fileBytes, nil
}
// convert to UTF-8 encoding
reader := transform.NewReader(bytes.NewReader(fileBytes), encoding.NewDecoder())
return ioutil.ReadAll(reader)
}
注意,示例代码中使用了第三方包 “golang.org/x/text/encoding/charset” 和 “golang.org/x/text/transform” 来处理编码转换。可以通过 go get 命令进行安装:
go get golang.org/x/text/encoding/charset
go get golang.org/x/text/transform




