Spaces:
Sleeping
Sleeping
| def read_markdown_file(file_path): | |
| """Reads a Markdown file and returns its content as a string. | |
| Args: | |
| file_path: The path to the Markdown file. | |
| Returns: | |
| The content of the file as a string, or an error message if the file | |
| cannot be read. | |
| """ | |
| try: | |
| with open(file_path, 'r', encoding='utf-8') as file: | |
| content = file.read() | |
| return content | |
| except FileNotFoundError: | |
| return f"Error: The file at {file_path} was not found." | |
| except Exception as e: | |
| return f"An error occurred: {e}" | |
| def replace_markdown_section_including_markers(filepath, start_marker, end_marker, new_content): | |
| """ | |
| Replaces a section in a Markdown file, including the start and end markers themselves. | |
| Args: | |
| filepath (str): The path to the Markdown file. | |
| start_marker (str): The unique string marking the start of the section. | |
| end_marker (str): The unique string marking the end of the section. | |
| new_content (str): The new content to insert, which will replace the old section | |
| and its markers. | |
| Returns: | |
| The modified content of the file as a string, or an error message if the file cannot be read. | |
| """ | |
| try: | |
| with open(filepath, 'r', encoding='utf-8') as f: | |
| content = f.read() | |
| start_index = content.find(start_marker) | |
| if start_index == -1: | |
| print(f"Error: Start marker '{start_marker}' not found in the file.") | |
| return | |
| # Find the end marker starting from after the start marker's position | |
| # This prevents issues if the end marker appears before the start marker later in the file | |
| end_index = content.find(end_marker, start_index) | |
| if end_index == -1: | |
| print(f"Error: End marker '{end_marker}' not found after start marker in the file.") | |
| return | |
| # Calculate the actual end of the section to be replaced (inclusive of end_marker) | |
| section_end_inclusive = end_index + len(end_marker) | |
| # Construct the modified content | |
| modified_content = ( | |
| content[:start_index] + # Content before the start marker | |
| new_content + # The new content replaces the entire old block | |
| content[section_end_inclusive:] # Content after the end marker | |
| ) | |
| return modified_content | |
| except FileNotFoundError: | |
| return f"Error: File '{filepath}' not found." | |
| except Exception as e: | |
| return f"An error occurred: {e}" | |