如何在文本文件中的特定位置追加字符串
How to append string somewhere specific in text file
我有一个文本文件,里面有这段文字:
<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())
我已经在网上寻找答案几个小时了,如果您能提供帮助,我将不胜感激。
为此,您需要以 r+
模式打开文件,以读取 和 写入文件。使用 file.seek()
将当前文件位置更改为文件中出现 <p>
的索引。然后写入新文本,加上文件的其余部分。
with open('webcode.html', 'r+') as file:
text = file.read()
i = text.index('<p>') + 3
file.seek(i)
file.write('Hello World' + text[i:])
我有一个文本文件,里面有这段文字:
<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())
我已经在网上寻找答案几个小时了,如果您能提供帮助,我将不胜感激。
为此,您需要以 r+
模式打开文件,以读取 和 写入文件。使用 file.seek()
将当前文件位置更改为文件中出现 <p>
的索引。然后写入新文本,加上文件的其余部分。
with open('webcode.html', 'r+') as file:
text = file.read()
i = text.index('<p>') + 3
file.seek(i)
file.write('Hello World' + text[i:])