I'd like to avoid writing a newline character to the end of a text file in python. This is a problem I have a lot, and I am sure can be fixed easily. Here is an example:
fileout = open('out.txt', 'w')
list = ['a', 'b', 'c', 'd']
for i in list:
fileout.write('%s\n' % (i))
This prints a \n character at the end of the file. How can I modify my loop to avoid this?
fileout = open('out.txt', 'w')
list = ['a', 'b', 'c', 'd']
fileout.write('\n'.join(list))
Here's a solution that avoids creating an intermediate string, which will be helpful when the size of the list is large. Instead of worrying about the newline at the end of the file, it puts the newline before the line to be printed, except for the first line, which gets handled outside the for loop.
fileout = open('out.txt', 'w')
mylist = ['a', 'b', 'c', 'd']
listiter = iter(mylist)
for first in listiter:
fileout.write(first)
for i in listiter:
fileout.write('\n')
fileout.write(i)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With