Reputation: 1278
I am trying to write three separate line in a text document based on input obtained from a dialogue window. I am sure this is a simple fix but I can't seem to write the three lines as separate lines. Would someone mind telling me what's wrong with this bit of code?
file = open('file.txt', 'wb')
file.write('input1')
file.write('input2')
file.write('input3')
The inputs should be on different lines but instead they come out as:
input1input2input3
Instead of:
input1
input2
input3
Upvotes: 2
Views: 357
Reputation: 143022
Try this:
file = open('file.txt', 'wb')
file.write('input1\n')
file.write('input2\n')
file.write('input3\n')
You are appending the newline character '\n'
to advance to the next line.
If you use the with
construct, it will automatically close the file for you:
with open('file.txt', 'wb') as file:
file.write('input1\n')
file.write('input2\n')
file.write('input3\n')
Also, consider using a different variable name in place of file
.
Upvotes: 8
Reputation: 17052
Your issue is that you haven't included newlines. Remember, Python is outputting like a typewriter--you don't tell it to go to a new line, it won't. The way to write a newline is \n
.
So,
file.write('\n'.join([input1, input2, input3]))
Would do it.
Upvotes: 2