Skip to content

Commit

Permalink
Fix modify_file_line to insert and append to file
Browse files Browse the repository at this point in the history
  • Loading branch information
JdFSilva committed Jan 15, 2025
1 parent 620932c commit 77604e3
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions labs/file_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,18 @@ def modify_file_line(file_path: str, content: Union[str | List[str]], line_numbe

temp_file_path = f"{file_path}.tmp"
skip_lines = 0

# Insert should be done in the next line
if not overwrite:
line_number += 1

content_written = False
try:
with open(file_path, "r") as original_file, open(temp_file_path, "w") as temp_file:
for current_line_number, line in enumerate(original_file, start=1):
if current_line_number == line_number:
temp_file.writelines(content)
content_written = True
if overwrite:
skip_lines = content_lines_count

Expand All @@ -46,6 +53,9 @@ def modify_file_line(file_path: str, content: Union[str | List[str]], line_numbe

temp_file.write(line)

if not content_written:
temp_file.writelines(content)

except Exception as e:
logger.error(f"Error modifying file {file_path}: {e}")
return
Expand Down

0 comments on commit 77604e3

Please sign in to comment.