1
0
Files
omc_api/lib/core/file/txt.go
2023-10-10 10:56:44 +08:00

80 lines
1.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package file
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
"ems.agt/lib/log"
)
// 写入Txt文件用,号分割 需要转换数据
// 例如:
// data := [][]string{}
// data = append(data, []string{"姓名", "年龄", "城市"})
// data = append(data, []string{"1", "2", "3"})
// err := file.WriterCSVFile(data, filePath)
func WriterTxtFile(data [][]string, filePath string) error {
// 获取文件所在的目录路径
dirPath := filepath.Dir(filePath)
// 确保文件夹路径存在
err := os.MkdirAll(dirPath, os.ModePerm)
if err != nil {
log.Errorf("创建文件夹失败 CreateFile %v", err)
}
// 创建或打开文件
file, err := os.Create(filePath)
if err != nil {
return err
}
defer file.Close()
// 创建一个 Writer 对象,用于将数据写入文件
writer := bufio.NewWriter(file)
for _, row := range data {
line := strings.Join(row, ",")
fmt.Fprintln(writer, line)
}
// 将缓冲区中的数据刷新到文件中
err = writer.Flush()
if err != nil {
log.Errorf("刷新缓冲区时发生错误:", err)
return err
}
return nil
}
// 读取Txt文件用,号分割 转换数组数据
func ReadTxtFile(filePath string) [][]string {
// 创建 map 存储 CSV 数据
arr := make([][]string, 0)
// 打开文本文件
file, err := os.Open(filePath)
if err != nil {
log.Fatal("无法打开文件:", err)
return arr
}
defer file.Close()
// 创建一个 Scanner 对象,用于逐行读取文件内容
scanner := bufio.NewScanner(file)
if scanner.Err() != nil {
log.Fatal("读取文件时出错:", scanner.Err())
return arr
}
for scanner.Scan() {
line := scanner.Text()
fields := strings.Split(line, ",")
arr = append(arr, fields)
}
return arr
}