Removing a line from text

2019-07-26 04:45发布

Say I have a text document. I have a line.I want to delete the text on that line and replace it with another text. How do I do this? There is nothing for this on the docs, thanks in advance!

2条回答
Viruses.
2楼-- · 2019-07-26 05:06

Untested: reads the lines of the file using .readlines() and then replaces the line number index in that list. Finally, it joins the lines and writes it to the file.

with open("file", "rw") as fp:
    lines = fp.readlines()
    lines[line_number] = "replacement line"
    fp.seek(0)
    fp.write("\n".join(lines))
查看更多
叛逆
3楼-- · 2019-07-26 05:06

To replace a line in QScintilla, you need to first select the line, like this:

    # as an example, get the current line
    line, pos = editor.getCursorPosition()
    # then select it
    editor.setSelection(line, 0, line, editor.lineLength(line))

Once the line is selected, you can replace it with:

    editor.replaceSelectedText(text)

If you want to replace a line with another line (which will be removed in the process):

    # get the text of the other line
    text = editor.text(line)
    # select it, so it can be removed
    editor.setSelection(line, 0, line, editor.lineLength(line))
    # remove it
    editor.removeSelectedText()
    # now select the target line and replace its text
    editor.setSelection(target, 0, target, editor.lineLength(target))
    editor.replaceSelectedText(text)        
查看更多
登录 后发表回答