本文介绍了删除文件的前N行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何高效地删除特定文件的前N行.
I was wondering how I can remove the first N lines of a specific file efficiently.
当然,我们可以将完整的文件加载到内存中,然后删除前N行并将完整的更改内容写入文件.
Of course, we can load the complete file into memory, then remove the first N lines and write the complete changed contents to the file.
但是,我想知道是否有办法比仅将所有内容加载到内存中更有效.
But, I was wondering if there is a way to make this more effective compared to just loading all contents in memory.
推荐答案
文件系统不支持从文件的任意位置删除,因此您至少需要自己重新编写整个文件.实施所需内容的常用方法是
Filesystems doesn't support deleting from arbitrary locations of a file, so you at least need to re-write the entire file yourself. The common way to implement what you need is to
- 打开一个临时文件,
- 从原始文件中读取小片段,例如在您的情况下,每次只能一行一行
- 仅将要保留在原始文件中的行写到临时文件中
- 完成后,将临时文件重命名为原始文件名.
这篇关于删除文件的前N行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!