python - 在 readlines() 之后添加 1 个单词
问题描述
我还在学习 python 并且对函数 readlines() 有疑问以下是我脚本的一部分:
f = open("demofile.txt", "r")
text = "".join(f.readlines())
print(text)
demofile.txt 包含:
This is the first line
This is the second line
This is the third line
现在我想在其中添加一个单词,所以我得到:
This is the first line
This is the second line
This is the third line
Example
我想到了一些简单的方法:
f = open("demofile.txt", "r")
text = "".join(f.readlines())."Example"
print(text)
但这不起作用(当然)我用谷歌搜索并环顾四周,但实际上并没有很好的关键字来搜索这个问题。希望有人能指出我正确的方向。
解决方案
.readlines()
list
您可以返回append()
它:
with open("demofile.txt") as txt:
lines = txt.readlines()
lines.append("Example")
text = "".join(lines)
print(text)
或者您可以解压缩文件对象,因为它是一个带有您要添加的单词txt
的新迭代器:list
with open("demofile.txt") as txt:
text = "".join([*txt, "Example"])
print(text)
推荐阅读
- wordpress - 高级自定义字段是否可以内置到自定义 wordpress 主题中,即当用户安装主题时可以立即确定字段?
- c# - 如何在 Unity 运行时更改 AudioMixer 源
- python - 如何在 wxpython 中刷新 Grid 类?
- javascript - 2个不同数组中的数组拼接函数怪异
- symfony - 为所有从包路由导入的前缀添加前缀时,如何在 Symfony 包的模板中生成 URL?
- windows-nt - 隐藏 NT 驱动功能的官方文档
- java - Spring Jsp中使用简单表单的问题
- c# - 在 URL.Action 中传递视图模型
- python - keyerror 名称“import/Placeholder”指的是不在图中的操作
- java - Java - 找不到文件异常 - 共享位置缺少斜杠