设为首页 加入收藏

TOP

【python技巧】替换文件中的某几行(二)
2023-09-09 10:25:29 】 浏览:113
Tags:python 技巧 文件中
find("end_sentence",start_index_1,) if start_index_1 == -1 or end_index_1 == -1: print("未找到待修改位置") return -1 # updated_content = file_content[:start_index_1]#获取这行代码之前的内容 updated_content += "start_sentence和end_sentence之间的sentence_1;\n" updated_content += "start_sentence和end_sentence之间的sentence_2;\n" updated_content +=file_content[end_index_1:] ##此时updated_content就是修改后的完整文件内容 if updated_content != "": with open(file_path, "w") as file: file.write(updated_content) else: print("修改失败") return -1
  1. 多行修改-局部替换
try:
    with open(file_path, "r") as file:
            file_content = file.read()
except Exception as e:
    return str(e)
# 设置改写内容
updated_content = ""
 # 查找修改
start_index_1 = file_content.find("start_sentence_1")#要确保查找元素的唯一性
end_index_1 = file_content.find("end_sentence_1",start_index_1,) 
start_index_2 = file_content.find("start_sentence_2",end_index_1)
end_index_2 = file_content.find("end_sentence_2",start_index_2,)
start_index_3 = file_content.find("start_sentence_3",end_index_2)
end_index_3 = file_content.find("end_sentence_3",start_index_3,)
start_index_4 = file_content.find("start_sentence_4",end_index_3)
end_index_4 = file_content.find("end_sentence_4",start_index_4,)

if (
     start_index_1 == -1
     or end_index_1 == -1
     or start_index_2 == -1
     or end_index_2 == -1
     or start_index_3 == -1
     or end_index_3 == -1
     or start_index_4 == -1
     or end_index_4 == -1
 ):
    print("未找到待修改位置")
     return -1

 # 
 updated_content = file_content[:start_index_1]#获取这行代码之前的内容
 updated_content += "start_sentence_1和end_sentence_1之间的内容"
 updated_content +=file_content[end_index_1:start_index_2]
 updated_content += "start_sentence_2和end_sentence_2之间的内容"
 updated_content +=file_content[end_index_2:start_index_3]
 updated_content += "start_sentence_3和end_sentence_3之间的内容"
 updated_content +=file_content[end_index_3:start_index_4]
 updated_content += "start_sentence_4和end_sentence_4之间的内容"
 updated_content += file_content[end_index_4:]

 ##此时updated_content就是修改后的完整文件内容
 if updated_content != "":
     with open(file_path, "w") as file:
         file.write(updated_content)
else:
    print("修改失败")
    return -1

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇《Python魔法大冒险》008 石像怪.. 下一篇Python垃圾回收

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目