python - 将空格转换为文本文件中的新行
问题描述
我正在尝试将所有空格转换为文本文件中的换行符,因此最后我将列出文本中所有单词的列表。
with open('keywords.txt', 'w+') as g:
replace = string.replace(" ","\n")
replace.writelines
可悲的是,这对我不起作用。
我愿意接受任何提示或想法,我不敢相信我无法得到需要 3-5 行代码的工作。
解决方案
'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)
推荐阅读
- java - 如何在设定的时间段内运行测试?
- javascript - 使用钩子将数据传递给子组件时遇到问题
- string - 检查字符串是否相等的算法,允许旋转和最多 K 次替换
- python - 从 Wikipedia 项目符号列表中提取名称仅返回每个字母的名字
- r - 是否可以将 rmarkdown 转换为 pandoc markdown,同时将代码块选项保留为代码块属性?
- python - 如何解决 OpenCV 中图像颜色错误的问题?
- node.js - 错误:尝试将长字符串从 nodejs 发送到 python 脚本时产生 ENAMETOOLONG
- matplotlib - Pgk.add("PyPlot") 失败;“包 ZMQ 没有版本”。macOS 10.15.7
- f# - F# 记录上是否有一种继承类型
- scala - SparkSQL-根据聚合向DataFrame添加新列