diff --git a/fileutil/file.go b/fileutil/file.go index bd89967..0f3fd84 100644 --- a/fileutil/file.go +++ b/fileutil/file.go @@ -11,6 +11,7 @@ import ( "crypto/sha1" "crypto/sha256" "crypto/sha512" + "encoding/csv" "errors" "fmt" "io" @@ -434,3 +435,21 @@ func Sha(filepath string, shaType ...int) (string, error) { return sha, nil } + +// MTime returns file modified time. +// Play: todo +func ReadCsvFile(filepath string) ([][]string, error) { + f, err := os.Open(filepath) + if err != nil { + return nil, err + } + defer f.Close() + + csvReader := csv.NewReader(f) + records, err := csvReader.ReadAll() + if err != nil { + return nil, err + } + + return records, nil +} diff --git a/fileutil/file_example_test.go b/fileutil/file_example_test.go index f42fbf8..85ab1c4 100644 --- a/fileutil/file_example_test.go +++ b/fileutil/file_example_test.go @@ -274,3 +274,14 @@ func ExampleSha() { // d22aba2a1b7a2e2f512756255cc1c3708905646920cb1eb95e45b531ba74774dbbb89baebf1f716220eb9cf4908f1cfc5b2a01267704d9a59f59d77cab609870 // } + +func ExampleReadCsvFile() { + content, err := ReadCsvFile("./testdata/test.csv") + + fmt.Println(content) + fmt.Println(err) + + // Output: + // [[Bob 12 male] [Duke 14 male] [Lucy 16 female]] + // +} diff --git a/fileutil/file_test.go b/fileutil/file_test.go index 5b5316b..9dca0b5 100644 --- a/fileutil/file_test.go +++ b/fileutil/file_test.go @@ -273,7 +273,7 @@ func TestMTime(t *testing.T) { } func TestSha(t *testing.T) { - assert := internal.NewAssert(t, "TestMTime") + assert := internal.NewAssert(t, "TestSha") sha1, err := Sha("./testdata/test.txt", 1) sha256, err := Sha("./testdata/test.txt", 256) @@ -284,3 +284,16 @@ func TestSha(t *testing.T) { assert.Equal("aa6d0a3fbc3442c228d606da09e0c1dc98c69a1cac3da1909199e0266171df35", sha256) assert.Equal("d22aba2a1b7a2e2f512756255cc1c3708905646920cb1eb95e45b531ba74774dbbb89baebf1f716220eb9cf4908f1cfc5b2a01267704d9a59f59d77cab609870", sha512) } + +func TestReadCsvFile(t *testing.T) { + assert := internal.NewAssert(t, "TestReadCsvFile") + + content, err := ReadCsvFile("./testdata/test.csv") + t.Log(content) + + assert.IsNil(err) + + assert.Equal(3, len(content)) + assert.Equal(3, len(content[0])) + assert.Equal("Bob", content[0][0]) +}