dongxiaoying5882 2013-10-29 17:22
浏览 82
已采纳

如何使用Golang在适当位置编辑大型文本文件?

I would like to edit one line of text from a large plain text file, and want to do this inplace, like Python's fileinput package:

fileinput.input(file, inplace=1)

My current approach is to read the whole file into []string and write them back, and I think this is terribly inefficient. So what is idiomatic way to do this in Golang?

Thanks.

  • 写回答

1条回答 默认 最新

  • dthhlf1777 2013-10-29 18:03
    关注

    Note that Python's inplace Fileinput works by copying the file to backup file and then redirecting the output to the original file. So it's not all that different from your current approach except that it uses a temporary file instead of loading it in memory. Loading it in memory could be ok, unless the file is very large.

    If the file is large, I suggest copying it to a temporary directory and then use the functions from the bufio package to read it line by line, modify what's needed and write the result to a new file with the same name as the original.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效