首页 > 解决方案 > 将空格转换为文本文件中的新行

问题描述

我正在尝试将所有空格转换为文本文件中的换行符,因此最后我将列出文本中所有单词的列表。

with open('keywords.txt', 'w+') as g:
    replace = string.replace(" ","\n")
    replace.writelines

可悲的是,这对我不起作用。

我愿意接受任何提示或想法,我不敢相信我无法得到需要 3-5 行代码的工作。

标签: python

解决方案


'w+' 将清空您的文件,并且您永远不会读取当前内容,并且 string.replace 不会那样工作。

with open('keywords.txt', 'r+') as g:
    s = g.read()
    s = s.replace(" ", "\n")
    g.seek(0)
    g.truncate()
    g.write(s)

推荐阅读