首页 > 解决方案 > 在 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)

但这不起作用(当然)我用谷歌搜索并环顾四周,但实际上并没有很好的关键字来搜索这个问题。希望有人能指出我正确的方向。

标签: pythonlistreadlines

解决方案


.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)

推荐阅读