Suppress linebreak on file.write

流过昼夜 提交于 2019-12-04 14:48:49

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???

You write a line breaks after every word:

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

Are these the line breaks you are seeing, or are there more additional ones?

You might need to perform a strip() on each wc[word]. Printing a single item from wc is would probably be enough to determine if there are already line breaks on those items that area causing this behavior.

Either that or the indentation on your final out.write("\n") is not doing what you intended it to do.

I think your indentation is wrong.

(also I took the liberty to make your if clause redundant and code more readable :)

for doc,wc in wordcounts.items()
   out.write(doc)
   for word in wordlist:
     out.write("\t%d" % wc.get(word,0))
   out.write("\n")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!