'\b'
only deletes when printing to a terminal (and not necessarily all terminals, though common *NIX shells and cmd.exe
should work). If the output is going to a file (or anywhere else besides a terminal), it's going to insert the literal ASCII backspace character.
If you're writing to anything but a terminal, the easiest way to undo what you've recently written would be to seek
back and truncate away the bit you don't want, e.g.:
import io
with open(filename, 'wb') as f:
... Do stuff ...
f.write(b'abcdefg')
... Do other stuff that doesn't write to the file ...
# Oh no, it shouldn't be abcdefg, I want xyz
f.seek(-len(b'abcdefg'), io.SEEK_CUR) # Seek back before bit you just wrote
f.truncate() # Remove everything beyond the current file offset
f.write(b'xyz') # Write what you really want
You can toggle between writing backspaces and doing seek and truncate based on whether you're outputting to a terminal; file-like objects have the .isatty()
method that returns True
when connected to a terminal, and False
otherwise.
Of course, if you're not connected to a terminal, and not writing to a seekable medium (e.g. piping your program to another program), then you're stuck. Once you've written, it's done, you can't undo it in the general case (there are exceptions involving buffering, but they're flaky and not worth covering).