-
-
Notifications
You must be signed in to change notification settings - Fork 123
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added a snippet for writing data to a cvs file
- Loading branch information
AmeerMoustafa
authored and
AmeerMoustafa
committed
Jan 7, 2025
1 parent
113488b
commit ab547f4
Showing
2 changed files
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
--- | ||
title: Write data to a CVS file | ||
description: An example of writing data to a cvs file | ||
author: AmeerMoustafa | ||
tags: file handling,cvs | ||
--- | ||
|
||
|
||
```go | ||
package main | ||
|
||
import ( | ||
"os" | ||
"log" | ||
"encoding/csv" | ||
) | ||
|
||
var data = [][]string{{"Line1", "Hello Readers of"}, {"Line2", "quicksnip.dev"}} | ||
|
||
func main() { | ||
file, err := os.Create("result.csv") | ||
checkError("Cannot create file", err) | ||
defer file.Close() | ||
|
||
writer := csv.NewWriter(file) | ||
defer writer.Flush() | ||
|
||
for _, value := range data { | ||
err := writer.Write(value) | ||
checkError("Cannot write to file", err) | ||
} | ||
} | ||
|
||
func checkError(message string, err error) { | ||
if err != nil { | ||
log.Fatal(message, err) | ||
} | ||
} | ||
``` |