Python:撤消写入文件
撤消对文件的写入的最佳方法是什么?如果我正在经历一个循环并一次写入一行,并且我想撤消之前的写入并将其替换为其他内容,我该怎么做呢?有什么想法吗?
提前致谢!
What is the best way to undo the writing to a file? If I'm going through a loop and writing one line at a time, and I want to undo the previous write and replace it with something else, how do I go about doing that? Any ideas?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正如其他人所指出的,这没有多大意义,最好在必要时才写。在您的情况下,您可以将“书写指针”保留在处理后面的一行。
伪代码:
如您所见,
previousItem
是唯一保存在内存中的项目,并且根据需要更新为“累积”。仅当下一个与该文件“相同”时,才会将其写入文件。当然,您确实可以回滚文件光标,只需跟踪最后一行开始的字节偏移量,然后在重写之前对其执行
fseek()
即可。乍一看,编码似乎更简单,但调试起来却是一场噩梦。as others have noted, this doesn't make much sense, it's far better not to write until you have to. in your case, you can keep the 'writing pointer' one line behind your processing.
pseudocode:
as you can see,
previousItem
is the only item kept in memory, and it's updated to 'accumulate' as needed. it's only written to file when the next one isn't "the same as" that one.of course, you could really rollback the file cursor, just keep track of the byte offset where the last line started and then do an
fseek()
to there before rewriting. at first it would seem simpler to code, but it's a total nightmare to debug.如前所述,您最好不要尝试撤消写入。不过,如果您确实想这样做,那也很简单:
只需记录要倒回的文件位置,向后查找,然后将文件截断到该位置即可。
这样做的主要问题是它不适用于流。您不能对 stdout、管道或 TCP 流执行此操作;仅针对真实文件。
As mentioned, you're best off not trying to undo writes. If you really want to do it, though, it's easy enough:
Just record the file position to rewind to, seek back to it, and truncate the file to that position.
The major problem with doing this is that it doesn't work on streams. You can't do this to stdout, or to a pipe or TCP stream; only to a real file.
尝试懒惰写入文件:直到您最终确定需要这样做才写入。
Try to write to your files lazily: Don't write until you are finally certain you need to do it.
如果您跟踪行号,您可以使用如下所示的内容:
If you keep track of the line numbers you can use something like this:
也许更好的做法是修改你的程序,这样它只会在你确定要写的情况下才写一行。为此,您的代码将类似于:
Perhaps a better thing to do would be to modify your program so that it will only write a line if you are sure that you want to write it. To do that your code would look something like: