Python: Writing raw strings to a file

python

Solution

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.

Problem

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?

Original source