英文:
Can not replace the content of a csv file in Go
问题
我使用os.OpenFile函数创建了一个csv文件(假设为"output.csv"),并使用os.Create和os.RDWR标志。我正在对这个文件进行一系列操作。在每次迭代中,我需要重写csv文件的内容("output.csv")。但是我的代码却将内容追加到了csv文件中。
英文:
I have created a csv file (assume "output.csv") using os.OpenFile with flags, os.Create and os.RDWR. I'm doing a series of operations on this file. In every Iteration, I need to rewrite the contents of the csv file ("output.csv"). But My code appends to the csv file.
答案1
得分: 3
在每次重写之前,截断文件并将其定位到开头。
示例:
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) // 取消或注释这些行以查看差异
			f.Seek(0, 0)  // 这些行
			for i := 0; i < n; i++ {
				f.WriteString(fmt.Sprintf("%d\n", i))
			}
		}
	} else {
		fmt.Println(err)
	}
}
英文:
Before each rewrite, truncate the file and seek to 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)
	}
}
答案2
得分: 1
在读写(os.RDWR)模式下打开文件会将内容追加到文件中。
解决方案:
以只读模式(os.RDONLY)打开文件进行读取,并在读取后关闭文件。
csvfile, _ := os.OpenFile("output.csv", os.O_RDONLY|os.O_CREATE, 0777)
csvfile.Close()
对于写入操作,以只写模式(os.WRONLY)打开文件进行写入,并在写入后关闭文件,这将覆盖文件而不是追加内容。
csvfile, _ := os.OpenFile("output.csv", os.O_WRONLY|os.O_CREATE, 0777)
csvfile.Close()
如果要追加内容,可以使用os.APPEND。
英文:
opening file in read and write(os.RDWR) mode appends to the file.
Sol:
open the file in read only mode(os.RDONLY) for reading and close it after reading.
csvfile ,_:= os.OpenFile("output.csv", os.O_RDONLY|os.O_CREATE, 0777)
csvfile.Close()
For writing, open the file in write only mode(os.WRONLY) and close it after writing, this overwrites the file rather than appending.
csvfile ,_:= os.OpenFile("output.csv", os.O_WRONLY|os.O_CREATE, 0777)
csvfile.Close()
for appending you could use os.APPEND
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论