Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid a Newline at End of File - Python

Tags:

python

list

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?

like image 819
bac Avatar asked Dec 16 '22 09:12

bac


2 Answers

fileout = open('out.txt', 'w')
list = ['a', 'b', 'c', 'd']
fileout.write('\n'.join(list))
like image 62
Winston Ewert Avatar answered Dec 18 '22 22:12

Winston Ewert


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)
like image 42
SingleNegationElimination Avatar answered Dec 18 '22 23:12

SingleNegationElimination