开发者社区> 问答> 正文

如何在文本文件中特定的位置附加字符串

我有一个文本文件,其中包含以下文本:

<html>
    <head>
        <title>My first webpage</title>
        <style>body{background-color:white; color:black}</style>
    </head>
    <body>
        <p></p>
    </body>
</html>

我想在之间添加一个字符串

在第七行。例如,如下所示:

<html>
    <head>
        <title>My first webpage</title>
        <style>body{background-color:white; color:black}</style>
    </head>
    <body>
        <p>This is an example</p>
    </body>
</html>

我编码了这个,但这显然是错误的

def makeHomepage():
    f = open("webcode.html", "r")
    line = f.readlines()

    for line in f:
        if line == "<p><p>":
            print(line + "Hello World")

print(makeHomepage())

我一直在网上寻找答案已有几个小时,因此,我们将不胜感激任何帮助。

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 19:11:46 454 0
1 条回答
写回答
取消 提交回答
  • 为了做到这一点,你需要在R +模式打开文件,读取和 写入文件。使用file.seek()将当前文件位置更改为索引,其中

    `出现在文件中。然后编写新文本,再加上文件的其余部分。

    with open('webcode.html', 'r+') as file:
        text = file.read()
        i = text.index('<p>') + 3
        file.seek(i)
        file.write('Hello World' + text[i:])
    

    回答来源:stackoverflow

    2020-03-24 19:11:54
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载