处理指定文件,将新内容插入到标记之间或在特定字符串上方或下方, 并包括开始和结束标记。 参数: - file_path: 文件路径 - new_content: 需要插入的新内容 - start_tag: 开始标记 - end_tag: 结束标记 - insert_position: 查找的插入位置字符串 - position_control: 控制插入到指定行的上方('above')或下方('below')
(file_path, new_content, start_tag, end_tag, insert_position, position_control='above')
| 1 | def process_file_plus(file_path, new_content, start_tag, end_tag, insert_position, position_control='above'): |
| 2 | """ |
| 3 | 处理指定文件,将新内容插入到标记之间或在特定字符串上方或下方, |
| 4 | 并包括开始和结束标记。 |
| 5 | |
| 6 | 参数: |
| 7 | - file_path: 文件路径 |
| 8 | - new_content: 需要插入的新内容 |
| 9 | - start_tag: 开始标记 |
| 10 | - end_tag: 结束标记 |
| 11 | - insert_position: 查找的插入位置字符串 |
| 12 | - position_control: 控制插入到指定行的上方('above')或下方('below') |
| 13 | """ |
| 14 | with open(file_path, 'r', encoding='utf-8') as file: |
| 15 | lines = file.readlines() |
| 16 | |
| 17 | start_index = -1 |
| 18 | end_index = -1 |
| 19 | |
| 20 | # 查找开始和结束标记的位置 |
| 21 | for i, line in enumerate(lines): |
| 22 | if start_tag in line: |
| 23 | start_index = i |
| 24 | elif end_tag in line: |
| 25 | end_index = i |
| 26 | break |
| 27 | |
| 28 | # 判断是否找到了开始和结束标记 |
| 29 | if start_index != -1 and end_index != -1 and start_index < end_index: |
| 30 | # 找到了标记,删除标记之间的内容并插入新的内容 |
| 31 | new_lines = lines[:start_index + 1] # 保留开始标记之前的内容(包含开始标记) |
| 32 | new_lines.append(new_content + '\n') # 添加新的内容 |
| 33 | new_lines.extend(lines[end_index:]) # 保留结束标记之后的内容 |
| 34 | else: |
| 35 | # 未找到开始和结束标记,查找插入位置字符串 |
| 36 | insert_index = -1 |
| 37 | for i, line in enumerate(lines): |
| 38 | if insert_position in line: |
| 39 | insert_index = i |
| 40 | break |
| 41 | |
| 42 | # 如果找到了插入位置字符串,则按位置控制参数插入内容 |
| 43 | if insert_index != -1: |
| 44 | if position_control == 'above': |
| 45 | # 插入到该行上方 |
| 46 | new_lines = ( |
| 47 | lines[:insert_index] + |
| 48 | [f"{start_tag}\n", new_content + '\n', f"{end_tag}\n"] + |
| 49 | lines[insert_index:] |
| 50 | ) |
| 51 | else: |
| 52 | # 插入到该行下方 |
| 53 | new_lines = ( |
| 54 | lines[:insert_index + 1] + |
| 55 | [f"{start_tag}\n", new_content + '\n', f"{end_tag}\n"] + |
| 56 | lines[insert_index + 1:] |
| 57 | ) |
| 58 | else: |
| 59 | # 如果没有找到插入位置字符串,则将新内容插入到文件末尾,并添加开始和结束标记 |
| 60 | new_lines = lines |
no outgoing calls
no test coverage detected