说我有一份文字文件。我有一行。我想删除该行上的文本并将其替换为另一个文本。我该怎么做呢?在文档上没有任何内容,提前感谢!
答案 0 :(得分:2)
未经测试:使用.readlines()读取文件的行,然后替换该列表中的行号索引。最后,它连接行并将其写入文件。
with open("file", "rw") as fp:
lines = fp.readlines()
lines[line_number] = "replacement line"
fp.seek(0)
fp.write("\n".join(lines))
答案 1 :(得分:2)
要替换QScintilla中的一行,您需要先选择一行,如下所示:
# as an example, get the current line
line, pos = editor.getCursorPosition()
# then select it
editor.setSelection(line, 0, line, editor.lineLength(line))
选择该行后,您可以将其替换为:
editor.replaceSelectedText(text)
如果您想用另一条线替换一条线(在此过程中将被移除):
# 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)