写入文本文件时,一些 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...”循环之外——但解释器将其视为那个循环。将空格转换为制表符解决了这个问题。
感谢您的输入。
最佳答案
如果您写入的字符串不包含任何 \n
,
file.write()
不会添加任何换行符。
但是您使用 out.write("\n")
为单词列表中的每个单词强制换行,这是您想要的吗?
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") #<--- NEWLINE ON EACH ITERATION!
也许你缩进 out.write("\n")
太远了???
关于python - 禁止在 file.write 上换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1826400/