Using \\b in Python 3

╄→尐↘猪︶ㄣ 提交于 2019-12-05 18:20:58
bastelflp

It depends on the terminal which is used and how it interprets the \b, e.g.

print('Text: ABC\b\b\bXYZ')

in the interactive console of PyCharm gives:

Text: ABC   XYZ

but executed in the comand line (cmd.exe) it gives:

Text: XYZ

This is explained in more detail here: https://stackoverflow.com/a/19926010/5276734

'\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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!