How could I write the "b" character in a file?

Question:

I am trying to write a file containing the "b" character as a string, but when open the file it is omitted.

Here is my code:

with open('proof.tex','w') as archivo:
    archivo.write('''documentclass[12pt, a4paper]{article}
begin{document}
$S=sum ^{100}_{i=0}a_{i}left( xright) $
end{document}''')

And here is the text generated in the output file:

egin{document}
$S=sum ^{100}_{i=0}a_{i}left( xright) $
end{document}
Asked By: user11536840

||

Answers:

It’s writing the backspace character, you’re just not seeing it in whatever external program you’re using.

Confirmation:

>>> with open('temptest.txt', 'w') as f:
...     f.write('123b456')
...
>>> with open('temptest.txt', 'r') as f2:
...     s = f2.read()
...
>>> s
'123x08456'

Try a tool like hexdump to look at your file and see the raw bytes. Most text editors don’t display b (U+0008, “backspace”) in any visible way.

If you’re looking to actually put a raw backslash followed by a raw b, on the other hand, you need to escape the backslash: Python interprets b as meaning U+0008, just like how n means a newline and t means a tab.

The easiest way is to use a raw string:

my_content = r'''b b b'''

Note the r (for “raw”) in front! This will have actual raw backslashes followed by actual raw bs.

You can also double the backslash:

my_content = '''\b \b \b'''

This has the same effect.

Answered By: Draconis
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.