I am trying to write Student Marks to a csv file in GO .
It is printing the desired 10 result per page with Println but is saving only the last value (not all 10) in csv .
This is what I am doing
Visitor visits
studentmarks.com/page=1Marks for 10 students are displayed and it is also saved in CSVVisitor clicks next page and he is navigated to
studentmarks.com/page=2Marks for another 10 students are displayed and it is also saved in subsequent column/rows in the CSV
and so on
fmt.Fprintf(w, KeyTemplate, key.fname, key.marks, key.lname ) is working fine and displays all 10 results per page but I am unable to save all 10 results in the CSV (with my current code, only the last result is saved).
Here is my snippet of the code that is responsible for printing and saving the results.
func PageRequest(w http.ResponseWriter, r *http.Request) {
// Default page number is 1
if len(r.URL.Path) <= 1 {
r.URL.Path = "/1"
}
// Page number is not negative or 0
page.Abs(page)
if page.Cmp(one) == -1 {
page.SetInt64(1)
}
// Page header
fmt.Fprintf(w, PageHeader, pages, previous, next)
// Marks for UID
UID, length := compute(start)
for i := 0; i < length; i++ {
key := UID[i]
fmt.Fprintf(w, key.fname, key.marks, key.lname, key.remarks)
// Save in csv
csvfile, err := os.Create("marks.csv")
if err != nil {
fmt.Println("Error:", err)
return
}
defer csvfile.Close()
records := [][]string{{key.fname, key.marks, key.lname, , key.remarks}}
writer := csv.NewWriter(csvfile)
for _, record := range records {
err := writer.Write(record)
if err != nil {
fmt.Println("Error:", err)
return
}
}
writer.Flush()
// Page Footer
fmt.Fprintf(w, PageFooter, previous, next)
}
How can I print and save (in csv) all the 10 results using go language?
marks.csvi.e.csvfile, err ... defer...out offorloop, e.g. after callingcompute(start).csvfile, err := os.Create("marks.csv") ... defer csvfile.Close()out of for loop. The other statements (fromrecords := ...) should be left as is.os.O_APPENDmode (as mentioned in the answer). But, please notes that whenever a visitor visits a page, the marks will be added to the CSV file, resulting duplicates marks in the file, e.g. when visitor access page 1 twice, marks from 10 students from page 1 will be added twice to the CSV file.