Skip to content

Instantly share code, notes, and snippets.

@brunnels
Created September 7, 2023 13:25
Show Gist options
  • Save brunnels/fb834cd602c45b87404e36d59214f35d to your computer and use it in GitHub Desktop.
Save brunnels/fb834cd602c45b87404e36d59214f35d to your computer and use it in GitHub Desktop.
unified diff
import difflib
import io
def generate_unified_diff(file1_path, file2_path, output_path):
with open(file1_path, 'r') as file1, open(file2_path, 'r') as file2:
lines1 = file1.readlines()
lines2 = file2.readlines()
diff = difflib.unified_diff(lines1, lines2, fromfile='config_old.txt', tofile='config_new.txt')
string_buffer = io.StringIO()
# Write the 'diff' lines to the in-memory buffer
string_buffer.writelines(diff)
diff_string = string_buffer.getvalue()
# Close the buffer
string_buffer.close()
return diff_string
if __name__ == "__main__":
config_old_path = "test.txt"
config_new_path = "test2.txt"
output_diff_path = "test.diff"
diff_output = generate_unified_diff(config_old_path, config_new_path, output_diff_path)
print(f"Unified diff generated and saved to {output_diff_path}")
print(diff_output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment