1

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!

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Pro-grammer
  • 862
  • 3
  • 15
  • 41
  • 2
    Have you tried open two files (source and destination), then using the `readline` function to go through each line on the source file, do your search/replace, and write it to the destination with `writeline`? – metatoaster Mar 16 '14 at 09:17
  • As its currently written, this question is a bit misleading. It's actually a follow-up from [this question](http://stackoverflow.com/q/22428152/984421) (see the comments). – ekhumoro Mar 16 '14 at 17:36

2 Answers2

2

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))
Ramchandra Apte
  • 4,033
  • 2
  • 24
  • 44
  • Despite being untested, the logic itself should work, even if the actual code might not, so +1. – Truerror Mar 16 '14 at 09:26
  • If the replacement makes the contents shorter, won't some of the original file be left at the end because it was not overwritten? – three_pineapples Mar 16 '14 at 09:41
  • @three_pineapples I think you're right. You'd probably want to remove the original instead of seek, but the basic idea remains so +1. – Oliver Mar 16 '14 at 17:26
  • Although there is nothing wrong with this answer, it's not actually relevant to the question (which is about the qscintilla editor control). – ekhumoro Mar 16 '14 at 17:44
2

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)        
ekhumoro
  • 115,249
  • 20
  • 229
  • 336