Writing a string (with newlines) in Python

I have to write lines with newlines and a specific structure for files in Python. When i do

stringtowrite = "abcd || efgh|| iklk" f = open(save_dir + "/" +count+"_report.txt", "w") f.write(stringtowrite) f.close() 

I get this error:

SyntaxError: EOL when scanning a string literal

How can I write a line as it is to a file without deleting new lines?

+6
source share
4 answers

You tried to change your line as follows:

 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""" 
+8
source

The simplest is to use python triple quotes (note the three single quotes)

 stringtowrite = '''abcd || efgh|| iklk''' 

any string literal with triple quotes will continue in the next 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 to do this.

+9
source

You can add the \ character at the end of each line, which indicates the continuation of the line on the next line, you can tangle the line instead of a single quote, or you can replace the literal of the newline in line \n .

+5
source

You can write newlines - \n - in your own line.

 stringtowrite = "abcd ||\nefgh||\niklk" 
+3
source

Source: https://habr.com/ru/post/895182/


All Articles