____tz_zs
在指定字符串前后插入指定字符串
过程:找到指定字符串的位置,拼接成新字符串。
#!/usr/bin/python2.7
# -*- coding:utf-8 -*-
"""
@author: tz_zs
"""
def init_index_html(file_path, head_title):
text = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>%s</title>
</head>
<body>
</body>
</html>
""" % head_title
with open(file_path, mode="w") as f:
f.write(text)
def _read_and_write_before(file_path, before="</body>", new_s="new_s"):
with open(file_path, mode="r") as f:
read_s = f.read()
index = read_s.index(before)
# index = read_s.find(before)
while 1:
if read_s[index] != "\n":
index -= 1
else:
break
with open(file_path, mode="w") as f:
f.write(read_s[:index] + new_s + read_s[index:])
def _read_and_write_after(file_path, after="<body>", new_s="new_s"):
with open(file_path, mode="r") as f:
read_s = f.read()
index = read_s.index(after)
# index = read_s.find(after)
index += len(after)
while 1:
if read_s[index] != "\n":
index += 1
else:
index += 1
break
with open(file_path, mode="w") as f:
f.write(read_s[:index] + new_s + read_s[index:])
def read_and_write(file_path, s, new_s):
with open(file_path, mode="r") as f:
read_s = f.read()
index = read_s.index(s)
# index = read_s.find("</body>")
with open(file_path, mode="w") as f:
f.write(read_s[:index] + new_s + read_s[index:])
if __name__ == '__main__':
init_index_html("index.html", "网页标题")
read_and_write("index.html", "</body>", "新插入的文字\n")
生成的文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>网页标题</title>
</head>
<body>
新插入的文字
</body>
</html>
在指定的行插入新字符串
过程:按行读取文件,得到一个元素为字符串的 list,list 的每一个元素即是文件的一行;在list的指定脚标插入目标字符串,得到的新 list 使用join函数组合成字符串,写入文件。
#!/usr/bin/python2.7
# -*- coding:utf-8 -*-
"""
@author: tz_zs
"""
def init_index_html(file_path, head_title):
text = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>%s</title>
</head>
<body>
</body>
</html>
""" % head_title
with open(file_path, mode="w") as f:
f.write(text)
def read_and_write(file_path, line, new_s):
read_list = []
with open(file_path, mode="r") as f:
read_s = f.readlines()
print(read_s)
"""
['\n',
' <!DOCTYPE html>\n',
' <html lang="en">\n',
' <head>\n',
' <meta charset="UTF-8">\n',
' <title>\xe7\xbd\x91\xe9\xa1\xb5\xe6\xa0\x87\xe9\xa2\x98</title>\n',
' </head>\n',
' <body>\n',
'\n',
' </body>\n',
' </html>\n',
' ']
"""
read_s.insert(line, new_s)
s = "".join(read_s)
with open(file_path, mode="w") as f:
f.write(s)
if __name__ == '__main__':
init_index_html("index.html", "网页标题")
read_and_write("index.html", -3, "新插入的文字2\n")
生成的文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>网页标题</title>
</head>
<body>
新插入的文字2
</body>
</html>
end