Removing A Line From Text
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 i
Solution 1:
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))
Solution 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)
Post a Comment for "Removing A Line From Text"