简体   繁体   English

如何写入文件的特定行?

[英]How to write to a specific line of a file?

Let's say I have a text file 假设我有一个文本文件

Line 1
Line 2
Line 3

I read through it and decide to change Line 2 to Line Two. 我通读了一下,决定将2号线更改为2号线。 Can I do that elegantly in Python without simply rewriting the file with the changes? 我可以在Python中优雅地做到这一点,而不必简​​单地用更改重写文件吗? I tried with file.seek() but I didn't really get anywhere with it nor I understand what it does exactly. 我尝试使用file.seek(),但是它并没有真正意义,也不知道它到底能做什么。

A file is a sequence of bytes. 文件是字节序列。 If you want to change something in the middle that requires more or fewer bytes to express, the rest of the file needs to resize. 如果要在中间更改需要更多或更少字节表示的内容,则文件的其余部分需要调整大小。

Because a file is a physical sequence of bytes on a storage medium, that means you need to rewrite the entire rest of the file. 因为文件是存储介质上字节的物理序列,所以这意味着您需要重写文件的其余部分 In other words, you need to move over everything following line 2 . 换句话说,您需要移至第二line 2之后的所有内容。

In practice, that means rewriting the file, as that is much easier to achieve. 实际上,这意味着重写文件,因为这更容易实现。

You want the power of in-place editing, which the fileinput module offers: 您需要就地编辑的功能,该功能由fileinput模块提供:

inplace-edit.py: inplace-edit.py:

import sys
import fileinput

for line in fileinput.input(sys.argv[1], inplace=1):
    line = line.rstrip() # Remove the new line
    if line == 'Line 2':
        line = 'Line two'
    print line

data.txt: data.txt:

Line 1
Line 2
Line 3

To run it: 要运行它:

python inplace-edit.py data.txt

The resulting data.txt: 产生的data.txt:

Line 1
Line two
Line 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM