13

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?

4 Answers 4

13

Have you tried to modify your string the following way:

stringtowrite = "abcd ||\nefgh||\niklk"

f = open(save_dir + os.path.sep +count+"_report.txt", "w")
f.write(stringtowrite)
f.close()

OR:

stringtowrite = """abcd ||
                   efgh||
                   iklk"""
Sign up to request clarification or add additional context in comments.

Comments

12

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.

3 Comments

Note you'll also get the leading whitespace using this.
Otherwise you'd have to do it all in one line: 'abcd ||\nefgh||\niklk'
Yep. I anticipate some further data format debugging for the author once this works. :)
5

You can add the \ character to the end of each line, which indicates that the line is continued on the next line, you can triple-quote the string instead of single-quoting it, or you can replace the literal newlines in the string with \n.

1 Comment

Putting a line continuation `\` at the end of the line will not embed a newline - it will just append the text from the next line.
4

You can write newlines – \n – into your string.

stringtowrite = "abcd ||\nefgh||\niklk"

2 Comments

Actually, the method from which I get an array of strings spits out strings with newlines. How do I replace each newline in the array of strings with '\' ?
If there are already newlines, there would be no need to add them - but then, I don't know your setup.

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.