18
votes

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?

8

8 Answers

38
votes

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])
5
votes
with open('target.txt','w') as out:
    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.")
    out.write('{}\n{}\n{}\n'.format(line1,line2,line3))
5
votes

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

target.write('''line 1
line 2
line 3''')
2
votes

I notice that this is a study drill from the book "Learn Python The Hard Way". Though you've asked this question 3 years ago, I'm posting this for new users to say that don't ask in stackoverflow directly. At least read the documentation before asking.

And as far as the question is concerned, using writelines is the easiest way.

Use it like this:

target.writelines([line1, line2, line3])

And as alkid said, you messed with the brackets, just follow what he said.

2
votes

It can be done like this as well:

target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
1
votes

Assuming you don't want a space at each new line use:

print("I'm going to write these to the file")
target.write("%s\n%s\n%s\n" % (line1, line2, line3))

This works for version 3.6

1
votes

this also works:

target.write("{}" "\n" "{}" "\n" "{}" "\n".format(line1, line2, line3))
0
votes
variable=10
f=open("fileName.txt","w+") # file name and mode
for x in range(0,10):
    f.writelines('your text')
    f.writelines('if you want to add variable data'+str(variable))
    # to add data you only add String data so you want to type cast variable  
    f.writelines("\n")