Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write multiple lines in a file in python

Tags:

python

I have the following code:

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

Here target is the file object and line1, line2, line3 are the user inputs. I want to use only a single target.write() command to write this script. I have tried using the following:

target.write("%s \n %s \n %s \n") % (line1, line2, line3)

But doesn't that put a string inside another string but if I use the following:

target.write(%s "\n" %s "\n" %s "\n") % (line1, line2, line3)

The Python interpreter(I'm using Microsoft Powershell) says invalid syntax. How would I able to do it?

like image 414
kartikeykant18 Avatar asked Jan 09 '14 12:01

kartikeykant18


People also ask

How do I make multiple lines in one Python?

You can have a string split across multiple lines by enclosing it in triple quotes. Alternatively, brackets can also be used to spread a string into different lines. Moreover, backslash works as a line continuation character in Python. You can use it to join text on separate lines and create a multiline string.

What is the Python function to write multiple lines in a file at once?

You can use write function to write multiple lines by separating lines by '\n'.


2 Answers

You're confusing the braces. Do it like this:

target.write("%s \n %s \n %s \n" % (line1, line2, line3))

Or even better, use writelines:

target.writelines([line1, line2, line3])
like image 55
aIKid Avatar answered Oct 15 '22 15:10

aIKid


another way which, at least to me, seems more intuitive:

target.write('''line 1
line 2
line 3''')
like image 25
jcklopp Avatar answered Oct 15 '22 15:10

jcklopp