I have to write strings with newlines and a specific structure to files in Python. When I do
stringtowrite = "abcd ||
efgh||
iklk"
f = open(save_dir + "/" +count+"_report.txt", "w")
f.write(stringtowrite)
f.close()
I'm getting this error:
SyntaxError: EOL while scanning string literal
How can I write the string as it is to a file without deleting the new lines?
In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.
You cannot split a statement into multiple lines in Python by pressing Enter . Instead, use the backslash ( \ ) to indicate that a statement is continued on the next line. In the revised version of the script, a blank space and an underscore indicate that the statement that was started on line 1 is continued on line 2.
In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.
Just use \n ; Python automatically translates that to the proper newline character for your platform.
The simplest thing is to use python's triple quotes (note the three single quotes)
stringtowrite = '''abcd ||
efgh||
iklk'''
any string literal with triple quotes will continue on a following line. You can use ''' or """.
By the way, if you have
a = abcd
b = efgh
c = iklk
I would recommend the following:
stringtowrite = "%s||\n%s||\n%s" % (a,b,c)
as a more readable and pythonic way of doing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With