禁止 file.write 上的换行符
写入文本文件时,输出文件中的某些 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...”循环之外,但解释器将其视为那个循环。将空格转换为制表符解决了这个问题。
感谢您的意见。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您写入的字符串不包含任何
\n
,则file.write()
不会添加任何换行符。但是您使用
out.write("\n")
为单词列表中的每个单词强制换行,这是您想要的吗?也许你缩进
out.write("\n")
太远了???file.write()
does not add any newlines if the string you write does not contain any\n
s.But you force a newline for each word in your word list using
out.write("\n")
, is that what you want?Perhaps you indented
out.write("\n")
too far???你在每个单词后面写一个换行符:
这些是你看到的换行符,还是还有更多的换行符?
You write a line breaks after every word:
Are these the line breaks you are seeing, or are there more additional ones?
您可能需要对每个
wc[word]
执行strip()
。从wc
打印单个项目可能足以确定导致此行为的那些项目上是否已经存在换行符。或者是您最终的out.write("\n") 上的缩进没有达到您的预期目的。
You might need to perform a
strip()
on eachwc[word]
. Printing a single item fromwc
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.我认为你的缩进是错误的。
(我还冒昧地让你的 if 子句变得多余,并使代码更具可读性:)
I think your indentation is wrong.
(also I took the liberty to make your if clause redundant and code more readable :)