【问题标题】:Suppress linebreak on file.write抑制 file.write 上的换行符
【发布时间】: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


【解决方案1】:

如果您编写的字符串不包含任何\ns,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")太多了???

【讨论】:

  • 不,我不希望每次迭代都有一个换行符——我希望每个文档都有一个换行符,单词之间用制表符分隔。
  • 好的,所以你最后一个 out.write 的意图太远了,应该与 wordlist -loop 中的 for 单词处于同一级别(即在你的问题中,还剩 4 个空格)
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

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

    无论是那个还是你最后的out.write("\n") 上的缩进都没有做你想要做的事情。

    【讨论】:

    • 我认为后者是正确的,前者具有误导性,因为他已经在做 "%d" % wc[word] 这表明 wc[word] 是整数,而不是可以是 .strip( )ped...
    【解决方案4】:

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

    (我还冒昧地让你的 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")
    

    【讨论】:

      猜你喜欢
      • 2011-01-27
      • 2015-11-01
      • 1970-01-01
      • 2011-09-15
      • 2010-10-14
      • 2016-08-23
      • 2011-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多