如何就地编辑大型文本文件

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

How to edit large text files in place

问题

我想要编辑一个大型纯文本文件中的一行文本,并且希望像Python的fileinput包一样在原地进行操作:

fileinput.input(file, inplace=1)

我目前的方法是将整个文件读入[]string中,然后将其写回文件,但我认为这种方法非常低效。那么在Go语言中,有没有更符合惯用方式的方法呢?

英文:

I would like to edit one line of text from a large plain text file, and want to do this in place, 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 Go?

答案1

得分: 6

请注意,Python的inplace Fileinput通过将文件复制到备份文件,然后将输出重定向到原始文件来工作。因此,它与您当前的方法并没有太大的区别,只是它使用了一个临时文件而不是将其加载到内存中。将其加载到内存中可能是可以的,除非文件非常大。

如果文件很大,我建议将其复制到临时目录,然后使用bufio包中的函数逐行读取文件,修改所需内容,并将结果写入与原始文件同名的新文件中。

英文:

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.

huangapple
  • 本文由 发表于 2013年10月30日 01:22:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/19665077.html
匿名

发表评论

匿名网友

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

确定