MCPcopy
hub / github.com/ChinaGodMan/UserScripts / process_file

Function process_file

utils/writer.py:71–103  ·  view source on GitHub ↗

处理指定文件,将新内容插入到标记之间

(file_path, new_content, start_tag, end_tag, insert_position)

Source from the content-addressed store, hash-verified

69
70
71def process_file(file_path, new_content, start_tag, end_tag, insert_position):
72 """处理指定文件,将新内容插入到标记之间"""
73 with open(file_path, 'r', encoding='utf-8') as file:
74 lines = file.readlines()
75 start_index = -1
76 end_index = -1
77 # 查找开始和结束标记的位置
78 for i, line in enumerate(lines):
79 if start_tag in line:
80 start_index = i
81 elif end_tag in line:
82 end_index = i
83 break
84 # 如果找到了这两个标记,删除中间的内容并插入新的内容
85 if start_index != -1 and end_index != -1 and start_index < end_index:
86 new_lines = lines[:start_index + 1] # 保留开始标记之前的内容(包括开始标记)
87 new_lines.append(new_content + '\n') # 添加新的内容
88 new_lines.extend(lines[end_index:]) # 保留结束标记之后的内容
89 else:
90 # 如果没有找到标记,根据参数选择插入到头部还是尾部
91 if insert_position == 'head':
92 new_lines = [f"{start_tag}\n", new_content + '\n', f"{end_tag}\n"] + lines
93 else:
94 new_lines = lines
95 if start_index == -1: # 如果开始标记没有找到
96 new_lines.append(f"\n{start_tag}\n")
97 new_lines.append(new_content + '\n')
98 if end_index == -1: # 如果结束标记没有找到
99 new_lines.append(f"{end_tag}\n")
100 # 写回文件
101 with open(file_path, 'w', encoding='utf-8', newline='\n') as file:
102 file.writelines(new_lines)
103 print(f"Processed {file_path}")

Callers 6

mainFunction · 0.90
mainFunction · 0.90
mainFunction · 0.90
fix_toc.pyFile · 0.90
mainFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected