禁止在file.write上换行 [英] Suppress linebreak on file.write

查看:237
本文介绍了禁止在file.write上换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在写入文本文件时,一些file.write实例后面跟着输出文件中的换行符,而另一些则不是。我不想要换行符,除非我告诉他们发生。代码:

  for doc,wc in wordcounts.items():
out.write(doc)#this works罚款,没有lineline
wordlist中的单词:
如果单词在wc:out.write(\t%d%wc [word])#linebreaks出现
else:out。在这些
out.write(\\\
)之后写(\ t0)##这一行有混合的空格/制表符

我错过了什么?



更新

我应该如何将代码粘贴到SO中。出于某种原因,在最后一行中出现了空格和制表符的混合,这样在TextMate中,它可见地出现在for ... ...循环之外 - 但是解释器将其视为那个循环。将空格转换为制表符解决了这个问题。



感谢您的输入。 如果你写的字符串不包含任何 \ n ,那么file.write() > s。



但是,您使用 out.write(\\\
为单词列表中的每个单词强制换行c $ c>,是你想要的吗?

  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出现
else:out.write(\ t0)#在每个
out.write(\\\
)#之后#---每个迭代的NEWLINE!

也许你缩进 out.write(\\\
太远了???


When writing to a text file, some of the file.write instances are followed by a linebreak in the output file and others aren't. I don't want linebreaks except where I tell them to occur. Code:

    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

What am I missing?

Update

I should have taken a clue from how the code pasted into SO. For some reason there was a mixture of spaces and tabs in the final line, such that in TextMate it visually appeared outside the "for word..." loop—but the interpreter was treating it as part of that loop. Converting spaces to tabs solved the problem.

Thanks for your input.

解决方案

file.write() does not add any newlines if the string you write does not contain any \ns.

But you force a newline for each word in your word list using out.write("\n"), is that what you want?

    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!

Perhaps you indented out.write("\n") too far???

这篇关于禁止在file.write上换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆