Avoid newlines at end of file - Python

I would like not to write a newline character at the end of a text file in python. This is a problem in which I have a lot, and I am sure that it can be easily fixed. 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 the \ n character at the end of the file. How to change my loop to avoid this?

+4
source share
4 answers
 fileout = open('out.txt', 'w') list = ['a', 'b', 'c', 'd'] fileout.write('\n'.join(list)) 
+8
source

In my opinion, a text file consists of lines of text. Lines end with a sequence of lines whose exact details are platform dependent. Thus, the correct text file should always contain exactly 1 sequence of lines per line.

In any case, you could probably solve this problem by either processing the last line differently, or by creating the entire file in memory and writing it as binary data, for fear of omitting the last one or two bytes, depending on your platform, the exact feed sequence format.

+1
source

Here is a solution that avoids creating an intermediate line, which will be useful when the list is large. Instead of worrying about a new line at the end of the file, it puts a new line before printing the line, with the exception of the first line, which is processed 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) 
+1
source

If you have very long lists that you don't want to convert to a single line with join() , the good old flag valibels come to the rescue:

 is_first_line = True for s in my_list: if is_first_line: # see, no write() in this branch is_first_line = False else: # we've just written a line; add a newline output.write('\n') output.write(s) 
+1
source

All Articles