0

I am trying to make the program write these in a new file. It is easy to do each line by itself, but combined is making problems.

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."


#this here results a syntax error..
target.write (\%r, \%r, \%r) % (line1, line2, line3)

#what do?
2
  • You can just write one string at a time, so you have to create one string containing all three strings (using format, string concatenation, ...). Commented Jan 23, 2019 at 14:43
  • do not use % in 2019 and stick any number of variables like here: stackoverflow.com/a/54313512/228117 Commented Jan 23, 2019 at 14:44

4 Answers 4

1

With python 3 you can use f strings

target.write (f"{line1} {line2} {line3}")

You can find much more about f-strings here on offical docs https://www.python.org/dev/peps/pep-0498/

Sign up to request clarification or add additional context in comments.

Comments

0

Try:

targe.write('{} {} {}'.format(line1,line2,line3))

or old format way:

target.write('%r %r %r' % (line1,line2,line3))

Comments

0

Using your current method of writing the lines, you need to have the "%r"s in a string, and the "% (line1, line2, line3)" needs to be in the "target.write()" function call

target.write("%r %r %r" % (line1, line2, line3)

But you cold also try using the writelines method

with open("test.txt", "w+") as file:
    file.writelines([line1, line2, line3])

You can also wrap your inputs into a loop to get an arbitrary amount of lines from the user

lines = []
lineCount = 5

for l in range(lineCount):
    lines.append(input("Line %d: " % l) + "\n")

with open("test.txt", "w+") as file:
    file.writelines(lines)

Comments

0

In Python you can concatenate strings using + operator, so try:

target.write(line1+line2+line3)

EDIT: Version with newlines:

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

1 Comment

Thanks, It worked! although when I tried to add a line break between them it erred.

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.