4

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?

0

5 Answers 5

4

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.

Sign up to request clarification or add additional context in comments.

Comments

4

You need to escape the last \ so it doesn't escape the end of string, but if you put it as part of a raw string, it won't get you exactly what you want:

>>> r'\r\n\\'
'\\r\\n\\\\'

Python's string literal concatenation, however, lets you mix raw and normal strings:

>>> r'\r\n' '\\'
'\\r\\n\\'

Comments

1

You could insert the raw string into the string via the format method. This ensures that the raw string will be inserted with the proper escaping.

Example:

mystring = "some string content {0}"
# insert raw string 
mystring = mystring.format(r"\r\n\\")

myfile = open("test.txt", "w")
myfile.write(mystring)
myfile.close()

Comments

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

Just escape your strings ^^

5 Comments

Well properly escaping the string here is more complicated: `\\r\\n\`. And it gets hairier later.
you actually want to write \n and \r to your file?
Yes, I want to write exactly \r\n\, as suggested by the r prefix.
Write them one character at a time, if its a `` escape it.
Please explain why you have to.
0

There is no way to have a string literal of arbitrary contents without escaping. You will always run into problems, since there is no way of for example having the "end-of-literal character", in this case ' there without escaping, as Python would be unable to tell if it is the end of the string literal or part of it.

And that's the entire reason why we have escaping in the first place. So the answer to your question is: You can't. Not in Python nor any other language.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.