Python2 在文档中插入数据
程序员文章站
2022-05-10 19:40:44
...
方法一:
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import os
def modifyFile(filename, content_add):
hit = 0
lines = []
lines_tmp = []
# 读取配置文件
with open(filename,'r') as f:
lines_tmp = f.readlines()
lines = lines_tmp
tmp = 0
for line in lines_tmp:
line = line.strip()
hit = hit+1
# 在第二次出现"XXXX"后增加content_add
if line == "XXXXX":
tmp = tmp + 1
if (content_add not in lines) and tmp == 2:
lines.insert(hit, content_add)
break
# 存储增加content_add后的文件
with open(filename,"w") as f:
for line in lines:
f.write(line)f __name__ == '__main__':
filename = 'C:/Users/Admin/Desktop/TEST.txt'
content_add = 'YYYYYY'
modifyFile(filename, content_add)
方法二:
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import os
def modifyFile(filename, content_add):
f = open(filename,'r+')
tmp = 0
lines = f.readlines()
f.seek(0)
for line in lines:
f.write(line)
if 'XXXXX' in line:
tmp = tmp + 1
if (content_add not in lines) and tmp == 2:
f.write(content_add)
f.close()
if __name__ == '__main__':
filename = 'C:/Users/Admin/Desktop/TEST.txt'
content_add = 'YYYYYY'
modifyFile(filename, content_add)