0

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( x\right) $
\end{document}''')

And here is the text generated in the output file:

egin{document}
$S=\sum ^{100}_{i=0}a_{i}\left( x\right) $
\end{document}
tzaman
  • 46,925
  • 11
  • 90
  • 115
  • 1
    A backslash character in a string literal is interpreted as starting a character escape. If you want a literal backslash character you should probably use a raw string literal: use `r'''` instead of just `'''`. – Daniel Pryden May 22 '19 at 02:19
  • Thanks, Daniel; but that does not work inside the write method. –  May 22 '19 at 02:28
  • What do you mean? String literals work the same way everywhere in Python. – Daniel Pryden May 22 '19 at 02:33
  • Using r''' ''' instead (as it is used with the print method) returned an error, but I could solve it using the double backslash. –  May 22 '19 at 02:38
  • I don't see how that's possible. If you can come up with a [mcve] to reproduce that, please open a new question about it! – Daniel Pryden May 22 '19 at 02:40
  • You are right; it worked as you said. I was, by mistake, leaving extra space between the r and the string. Thanks for your help. –  May 22 '19 at 02:49
  • The issue is that you **do not want** to write "the \b character" into the file. "The \b character" is a backspace character, but the file **actually should contain** a backslash followed by a lowercase b. – Karl Knechtel Aug 07 '22 at 05:46

1 Answers1

0

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('123\b456')
...
>>> with open('temptest.txt', 'r') as f2:
...     s = f2.read()
...
>>> s
'123\x08456'

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.

Draconis
  • 3,209
  • 1
  • 19
  • 31