【发布时间】:2009-12-01 14:08:25
【问题描述】:
写入文本文件时,一些 file.write 实例后跟输出文件中的换行符,而另一些则没有。我不想要换行符,除非我告诉它们发生。代码:
for doc,wc in wordcounts.items():
out.write(doc) #this works fine, no linebreak
for word in wordlist:
if word in wc: out.write("\t%d" % wc[word]) #linebreaks appear
else: out.write("\t0") #after each of these
out.write("\n") #this line had mixed spaces/tabs
我错过了什么?
更新
我应该从代码如何粘贴到 SO 中获得线索。出于某种原因,最后一行中混合了空格和制表符,因此在 TextMate 中它在视觉上出现在“for word...”循环之外——但解释器将其视为那个循环。将空格转换为制表符解决了这个问题。
感谢您的意见。
【问题讨论】:
-
将那些
write()调用交换为print可能有助于您可视化写入out的内容。只需确保使用print foo,(尾随逗号),以免添加换行符。
标签: python file line-breaks