1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-09 07:02:29 +08:00

feat: add WirteCsvFile

This commit is contained in:
dudaodong
2023-06-13 14:56:43 +08:00
parent d20f8783b2
commit f3382ceac9
6 changed files with 190 additions and 75 deletions

View File

@@ -370,7 +370,7 @@ func MTime(filepath string) (int64, error) {
return f.ModTime().Unix(), nil
}
// MTime returns file sha value, param `shaType` should be 1, 256 or 512.
// Sha returns file sha value, param `shaType` should be 1, 256 or 512.
func Sha(filepath string, shaType ...int) (string, error) {
file, err := os.Open(filepath)
if err != nil {
@@ -420,6 +420,27 @@ func ReadCsvFile(filepath string) ([][]string, error) {
return records, nil
}
// WriteCsvFile write content to target csv file.
func WriteCsvFile(filepath string, records [][]string, append bool) error {
flag := os.O_RDWR | os.O_CREATE
if append {
flag = flag | os.O_APPEND
}
f, err := os.OpenFile(filepath, flag, 0644)
if err != nil {
return err
}
defer f.Close()
writer := csv.NewWriter(f)
writer.Comma = ','
return writer.WriteAll(records)
}
// WriteStringToFile write string to target file.
func WriteStringToFile(filepath string, content string, append bool) error {
flag := os.O_RDWR | os.O_CREATE

View File

@@ -268,7 +268,7 @@ func TestSha(t *testing.T) {
func TestReadCsvFile(t *testing.T) {
assert := internal.NewAssert(t, "TestReadCsvFile")
content, err := ReadCsvFile("./testdata/test.csv")
content, err := ReadCsvFile("./testdata/demo.csv")
t.Log(content)
assert.IsNil(err)
@@ -278,6 +278,27 @@ func TestReadCsvFile(t *testing.T) {
assert.Equal("Bob", content[0][0])
}
func TestWriteCsvFile(t *testing.T) {
assert := internal.NewAssert(t, "TestWriteCsvFile")
csvFilePath := "./testdata/test1.csv"
content := [][]string{
{"Lili", "22", "female"},
{"Jim", "21", "male"},
}
err := WriteCsvFile(csvFilePath, content, false)
assert.IsNil(err)
readContent, err := ReadCsvFile(csvFilePath)
assert.IsNil(err)
assert.Equal(2, len(readContent))
assert.Equal(3, len(readContent[0]))
assert.Equal("Lili", content[0][0])
}
func TestWriteStringToFile(t *testing.T) {
assert := internal.NewAssert(t, "TestWriteStringToFile")

2
fileutil/testdata/test1.csv vendored Normal file
View File

@@ -0,0 +1,2 @@
Lili,22,female
Jim,21,male
1 Lili 22 female
2 Jim 21 male