I want to remove a line in a file; currently I’m creating a new file, copying every line except the one I want to remove, deleting the old file and renaming the new one as the same filename as the old one. Is there a better way to remove a line?
f = open('./todo.txt', 'r')
newF = open('./todo-run.txt', 'a')
lines = f.readlines()
cLine = lines[int(index) - 1]
for line in lines:
if line != cLine:
newF.write(line)
f.close()
newF.close()
os.remove('./todo.txt')
shutil.move('./todo-run.txt', './todo.txt')
A solution in sed, which you might call using “subprocess”. Ex, to delete line 18 do: