Is it possible to modify lines in a file in-place?

前端 未结 5 1127
眼角桃花
眼角桃花 2020-11-22 08:29

Is it possible to parse a file line by line, and edit a line in-place while going through the lines?

5条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 09:01

    If you only intend to perform localized changes that do not change the length of the part of the file that is modified (e.g. changing all characters to lower case), then you can actually overwrite the old contents of the file dynamically.

    To do that, you can use random file access with the seek() method of a file object.

    Alternatively, you may be able to use an mmap object to treat the whole file as a mutable string. Keep in mind that mmap objects may impose a maximum file-size limit in the 2-4 GB range on a 32-bit CPU, depending on your operating system and its configuration.

提交回复
热议问题