开发者

Avoid a Newline at End of File - Python

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)


In my opinion, a text file consists of lines of text. Lines are terminated with a line feed sequence, the exact details of which is platform-specific. Thus, a proper text file must always contain exactly 1 line feed sequence per line.

Anyway, you could probably solve this by either treating the last line differently, or building up the entire file in-memory and writing it as binary data, taking care to omit the final one or two bytes, depending on your platform's line feed sequence's exact format.


If you have really long lists that you don't want to convert into one string with join(), good old flag varaibles come to 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜