在file.write上禁止换行

时间:2009-12-01 14:08:26

标签: python file line-breaks

写入文本文件时,某些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中, visual 出现在“for word ...”循环之外 - 但是解释器将其作为那个循环。将空格转换为制表符解决了这个问题。

感谢您的意见。

4 个答案:

答案 0 :(得分:7)

如果您编写的字符串不包含任何file.write(),则

\n不会添加任何换行符。

但是你使用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")太远了???

答案 1 :(得分:1)

你在每个单词后写一个换行符:

for word in wordlist:
    ...
    out.write("\n")

这些是你看到的换行符,还是还有更多的换行符?

答案 2 :(得分:1)

您可能需要在每个strip()上执行wc[word]。从wc打印单个项目可能足以确定那些区域是否已存在换行符导致此行为。

最终out.write("\n")上的缩进或缩进不符合您的预期。

答案 3 :(得分:0)

我认为你的缩进是错误的。

(我也冒昧地让你的if子句冗余,代码更具可读性:)

for doc,wc in wordcounts.items()
   out.write(doc)
   for word in wordlist:
     out.write("\t%d" % wc.get(word,0))
   out.write("\n")