且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python:读取一行并写回同一行

更新时间:2022-12-10 07:38:24

在文本文件中更新行-非常困难

SO中的许多问题都试图读取文件并立即对其进行更新.

Updating lines in place in text file - very difficult

Many questions in SO are trying to read the file and update it at once.

尽管这在技术上是可行的,但这是非常困难的.

While this is technically possible, it is very difficult.

(文本)文件不是按行组织在磁盘上的,而是按字节组织的.

(text) files are not organized on disk by lines, but by bytes.

问题是,旧行上的读取字节数通常与新行上的字节数不同,这会弄乱生成的文件.

The problem is, that read number of bytes on old lines is very often different from new one, and this mess up the resulting file.

虽然听起来效率低下,但从编程角度来看,这是最有效的方法.

While it sounds inefficient, it is the most effective way from programming point of view.

仅从一侧读取文件,在另一侧写入另一个文件,关闭文件,然后从旧文件中复制新创建的内容.

Just read from file on one side, write to another file on the other side, close the files and copy the content from newly created over the old one.

或者在内存中创建文件,并在关闭旧文件后最后重写旧文件.

Or create the file in memory and finally do the writing over the old one after you close the old one.