python - 禁止在 file.write 上换行

标签 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 中它视觉上出现在“for word...”循环之外——但解释器将其视为那个循环。将空格转换为制表符解决了这个问题。

感谢您的输入。

最佳答案

如果您写入的字符串不包含任何 \n

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") 太远了???

关于python - 禁止在 file.write 上换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1826400/

相关文章:

Python:列表在for循环后不发生变化

python - 从函数声明中收集参数名称

python - xarray select\interpolate 自定义一维切片 auf 多维数据(又名 zip 与 itertools.product)

java - 创建不带扩展名的文件

JavaScript--使 <BR/> 标记处于事件和非事件状态

regex - 使用 Notepad++ 双换行符

python - 将 Python 移植到嵌入式系统

C++ : File format error

python:哪里需要真正的内置文件对象?

python - 为什么 Python 看不到文件中的所有行?