Skip to content

Commit 7569a1a

Browse files
committed
feat: added read csv file function
1 parent ec50607 commit 7569a1a

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

filesystem/errors.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
package filesystem
22

3+
import (
4+
"errors"
5+
)
6+
37
var (
48
ErrUnableToReadFile = "unable to read file: %v"
9+
ErrNilFile = errors.New("file cannot be nil")
510
)

filesystem/read_files.go

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package filesystem
22

33
import (
4+
"encoding/csv"
45
"fmt"
56
"os"
67
)
@@ -13,3 +14,67 @@ func ReadFile(path string) ([]byte, error) {
1314
}
1415
return file, nil
1516
}
17+
18+
// OpenFile opens the file from the given path
19+
func OpenFile(path string) (*os.File, error) {
20+
// Open the CSV file
21+
file, err := os.Open(path)
22+
if err != nil {
23+
return nil, fmt.Errorf("failed to open file: %w", err)
24+
}
25+
return file, nil
26+
}
27+
28+
// CloseFile closes the file
29+
func CloseFile(file *os.File) error {
30+
if file != nil {
31+
err := file.Close()
32+
if err != nil {
33+
return fmt.Errorf("failed to close file: %w", err)
34+
}
35+
}
36+
return nil
37+
}
38+
39+
// ReadCSVFile reads a CSV file and returns a slice of string slices
40+
func ReadCSVFile(file *os.File, readHeaders bool) (
41+
*[][]string,
42+
*[]string,
43+
error,
44+
) {
45+
// Check if the file is nil
46+
if file == nil {
47+
return nil, nil, ErrNilFile
48+
}
49+
50+
// Defer closing the file
51+
defer func(file *os.File) {
52+
if err := CloseFile(file); err != nil {
53+
fmt.Println(err)
54+
}
55+
}(file)
56+
57+
// Create a new CSV reader
58+
reader := csv.NewReader(file)
59+
60+
// Read the header line
61+
var headers []string
62+
var err error
63+
if readHeaders {
64+
headers, err = reader.Read()
65+
if err != nil {
66+
return nil, nil, fmt.Errorf("failed to read header line: %w", err)
67+
}
68+
}
69+
70+
// Read all records from the CSV file
71+
records, err := reader.ReadAll()
72+
if err != nil {
73+
return nil, nil, fmt.Errorf("failed to read CSV file: %w", err)
74+
}
75+
76+
if readHeaders {
77+
return &records, &headers, nil
78+
}
79+
return &records, nil, nil
80+
}

0 commit comments

Comments
 (0)