Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Writing raw strings to a file

Tags:

python

I want to generate C code with a Python script, and not have to escape things. For example, I have tried:

myFile.write(someString + r'\r\n\')

hoping that a r prefix would make things work. However, I'm still getting the error:

myFile.write(someString + ur'\r\n\')
                                   ^
SyntaxError: EOL while scanning string literal

How can I write raw strings to a file in Python?

like image 697
Randomblue Avatar asked Jan 17 '23 11:01

Randomblue


1 Answers

Python raw stings can't end with a backslash.

However, there are workarounds.

You can just add a whitespace at the end of the string:

>>> with open("c:\\tmp\\test.txt", "w") as myFile:
...   myFile.write(someString + r'\r\n\ ')

You propably don't bother with that, so that may be a solution.

Assume someString is Hallo.

This will write Hallo\r\n\_ to the file, where _ is a space.

If you don't like the extra space, you can remove it like this:

>>> with open("c:\\tmp\\test.txt", "w") as myFile:
...   myFile.write(someString + r'\r\n\ '[:-1])

This will write Hallo\r\n\ to the file, without the extra whitespace, and without escaping the backslash.

like image 187
sloth Avatar answered Jan 29 '23 08:01

sloth