Reputation: 116283
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?
Upvotes: 4
Views: 13093
Reputation: 2685
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()
Upvotes: 1
Reputation: 101052
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.
Upvotes: 4
Reputation: 35069
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\\'
Upvotes: 4
Reputation: 9826
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.
Upvotes: 0
Reputation: 34698
myFile.write(someString + r'\r\n\\')
Just escape your strings ^^
Upvotes: 0