无法在Go中替换CSV文件的内容。

huangapple go评论68阅读模式
英文:

Can not replace the content of a csv file in Go

问题

我使用os.OpenFile函数创建了一个csv文件(假设为"output.csv"),并使用os.Createos.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 (
	&quot;fmt&quot;
	&quot;os&quot;
)

func main() {
	if f, err := os.Create(&quot;test.csv&quot;); err == nil {
		defer f.Close()
		for n := 10; n &gt; 0; n-- {
			f.Truncate(0) // comment or uncomment
			f.Seek(0, 0)  // these lines to see the difference
			for i := 0; i &lt; n; i++ {
				f.WriteString(fmt.Sprintf(&quot;%d\n&quot;, 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(&quot;output.csv&quot;, 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(&quot;output.csv&quot;, os.O_WRONLY|os.O_CREATE, 0777)
csvfile.Close()

for appending you could use os.APPEND

huangapple
  • 本文由 发表于 2015年6月25日 20:37:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/31050656.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定