在 Go 中追加到文件
所以我可以像这样从本地文件中读取:
data, error := ioutil.ReadFile(name)
并且我可以写入本地文件
ioutil.WriteFile(filename, content, permission)
但是如何附加到文件?有内置方法吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这个答案适用于 Go1:
This answers works in Go1:
Go 文档有一个完美示例:
Go docs has a perfect example :
弄清楚了
详细信息
Figured it out
More info
通过向 os.OpenFile 函数添加标志,对 golang 站点中提供的函数进行了轻微更改,该函数默认只允许读取文件,而不允许在其他功能中进行编辑。
Made a slight change from the one provided in the golang site by adding flags to the
os.OpenFile
function which by default will only allow reading of a file and not editing amongst other features....我会使用 fmt.Fprintf,因为接受写入器...并且连接或文件将成为写入器并且易于以字符串方式写入...
我希望这有所帮助!
哈维尔,
... I would use fmt.Fprintf, because accept a writer... and a connection or files will be a writer and easy to write in a way of string...
I hope this help!
Javier,
如果您还想创建文件
f, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
If you also want to create the file
f, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
假设您要将文件
current
的内容添加到文件all
中,那么下面的代码就可以工作:Let's say you want to add the contents of file
current
to the fileall
, then below code is working:2024:如 m0j0 -a-file-in-go?noredirect=1#comment139306032_7151261">评论,因为OP (2011),Go 1.16,2021 年第 1 季度 附带 弃用
io/ioutil
回到问题:
实际上有一个建议来实现这样的方法!
请参阅提案 30159 和代码PR 30157,2019 年第一季度:
被拒绝(及其相关问题30207:提案:cmd/go/internal/lockedfile:添加
Append
功能 也被冻结了Ian Lance Taylor 解释:
因此,其他答案在您自己的项目中很好,但在标准库中则不然,如 Rob Pike 提到:
2024: as m0j0 mentioned in the comments that, since the OP (2011), Go 1.16, Q1 2021 came with the deprecation of
io/ioutil
Back to the question:
There actually was a proposal to implement such a method!
See proposal 30159 and the code PR 30157, in Q1 2019:
It was rejected (and its associated issue 30207: proposal: cmd/go/internal/lockedfile: add
Append
function is also frozen.Ian Lance Taylor explained:
So the other answers are fine in your own project, but not in the standard library, as Rob Pike mentioned: