我希望在Python中避免向文本文件末尾写入换行符。这是我经常遇到的问题,我相信很容易解决。以下是一个示例:
fileout = open('out.txt', 'w')
list = ['a', 'b', 'c', 'd']
for i in list:
fileout.write('%s\n' % (i))
这会在文件末尾打印一个 \n 字符。我该如何修改我的循环以避免这种情况?
fileout = open('out.txt', 'w')
list = ['a', 'b', 'c', 'd']
fileout.write('\n'.join(list))
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)
如果您有非常长的列表,不想使用join()
将其转换为一个字符串,那么好老的标志变量就可以派上用场:
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)
StopIteration
。使用for循环而不是try、next、except StopIteration似乎不那么奇怪。 - SingleNegationElimination