How to Read CSV File in Go: Simple Guide with Example
In Go, you can read a CSV file using the
encoding/csv package by opening the file with os.Open, creating a CSV reader with csv.NewReader, and then reading the records with ReadAll or Read. This lets you easily process CSV data line by line or all at once.Syntax
To read a CSV file in Go, you typically follow these steps:
- Open the file using
os.Open. - Create a CSV reader with
csv.NewReaderpassing the file. - Read the CSV data using
ReadAllto get all records orReadto read line by line. - Handle any errors that occur during these steps.
go
file, err := os.Open("filename.csv") if err != nil { // handle error } defer file.Close() reader := csv.NewReader(file) records, err := reader.ReadAll() if err != nil { // handle error } // use records
Example
This example shows how to open a CSV file named data.csv, read all its rows, and print each row's fields.
go
package main import ( "encoding/csv" "fmt" "log" "os" ) func main() { file, err := os.Open("data.csv") if err != nil { log.Fatal(err) } defer file.Close() reader := csv.NewReader(file) records, err := reader.ReadAll() if err != nil { log.Fatal(err) } for i, record := range records { fmt.Printf("Row %d: %v\n", i+1, record) } }
Output
Row 1: [Name Age City]
Row 2: [Alice 30 New York]
Row 3: [Bob 25 Los Angeles]
Row 4: [Charlie 35 Chicago]
Common Pitfalls
Common mistakes when reading CSV files in Go include:
- Not closing the file after opening it, which can cause resource leaks.
- Ignoring errors returned by
os.OpenorReadAll, leading to crashes or unexpected behavior. - Assuming all rows have the same number of fields without checking.
- Not handling CSV files with different delimiters or quoting rules (the
csv.Readercan be configured for these).
go
/* Wrong way: ignoring errors and not closing file */ file, _ := os.Open("data.csv") reader := csv.NewReader(file) records, _ := reader.ReadAll() fmt.Println(records) /* Right way: handle errors and close file */ file, err := os.Open("data.csv") if err != nil { log.Fatal(err) } defer file.Close() reader := csv.NewReader(file) records, err := reader.ReadAll() if err != nil { log.Fatal(err) } fmt.Println(records)
Quick Reference
Here is a quick summary of key functions and methods to read CSV files in Go:
| Function/Method | Description |
|---|---|
| os.Open(filename) | Opens the CSV file for reading. |
| csv.NewReader(io.Reader) | Creates a new CSV reader from the file. |
| ReadAll() | Reads all records from the CSV file at once. |
| Read() | Reads one record (line) at a time from the CSV file. |
| Close() | Closes the opened file to free resources. |
Key Takeaways
Use os.Open to open the CSV file and defer file.Close to avoid resource leaks.
Use encoding/csv.NewReader to create a CSV reader and ReadAll or Read to get data.
Always check and handle errors from file operations and CSV reading.
CSV files may have different formats; configure csv.Reader if needed.
Iterate over records to process CSV data row by row or all at once.