Can't replace CSV file content in Go
I created a csv file (assume "output.csv") using os.OpenFile
with flags, os.Create
and os.RDWR
. I am doing a series of operations on this file. In each iteration, I need to rewrite the content of the csv file ("output.csv"). But my code is being added to the csv file.
Before each rewriting, trim the file and look for the beginning. Example:
package main
import (
"fmt"
"os"
)
func main() {
if f, err := os.Create("test.csv"); err == nil {
defer f.Close()
for n := 10; n > 0; n-- {
f.Truncate(0) // comment or uncomment
f.Seek(0, 0) // these lines to see the difference
for i := 0; i < n; i++ {
f.WriteString(fmt.Sprintf("%d\n", i))
}
}
} else {
fmt.Println(err)
}
}
opening a file in read / write mode (os.RDWR) appended to the file.
Salt: open the file in read-only mode ( os.RDONLY ) to read and close it after reading.
csvfile ,_:= os.OpenFile("output.csv", os.O_RDONLY|os.O_CREATE, 0777)
csvfile.Close()
To write, open the file in write-only mode ( os.WRONLY ) and close it after writing, this will overwrite the file, not add.
csvfile ,_:= os.OpenFile("output.csv", os.O_WRONLY|os.O_CREATE, 0777)
csvfile.Close()
to add you can use os.APPEND