Can't replace CSV file content in Go
2 answers
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)
}
}
+3
source to share
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
0
source to share