Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork937
-
Can I use GitPython to diff two individual files that are not in a Git repo? Using the Diff class? |
BetaWas this translation helpful?Give feedback.
All reactions
Replies: 2 comments
-
No, but I am sure there are python packages that will do so. What follows is LLM generated, and seems plausible, but is untested.
To create a difference (diff) between two files in Python, you can use the Here's how you can do it using both methods: Using difflibThe importdifflibdefcompare_files(file1,file2):withopen(file1,'r')asf1:lines1=f1.readlines()withopen(file2,'r')asf2:lines2=f2.readlines()diff=difflib.unified_diff(lines1,lines2,fromfile=file1,tofile=file2)return'\n'.join(diff)if__name__=="__main__":file1='path/to/file1.txt'file2='path/to/file2.txt'print(compare_files(file1,file2)) Using unidiffIf you need more advanced features or better performance, consider using the pip install unidiff Here’s an example of how to use fromunidiffimportPatchedFiledefcreate_diff(file1,file2):withopen(file1,'r')asf1:lines1=f1.readlines()withopen(file2,'r')asf2:lines2=f2.readlines()diff=difflib.unified_diff(lines1,lines2,fromfile=file1,tofile=file2)patch=PatchedFile.from_string('\n'.join(diff))returnstr(patch)if__name__=="__main__":file1='path/to/file1.txt'file2='path/to/file2.txt'print(create_diff(file1,file2)) In this example, we first generate the diff using Explanation
Choose the method that best fits your needs based on whether you want simplicity (using |
BetaWas this translation helpful?Give feedback.
All reactions
-
@Byron Thanks a lot! I want to use the four Git diff algorithms (Myers, Minimal, Histogram, and Patience) in Python code, but it seems that no Python module has such APIs. |
BetaWas this translation helpful?Give feedback.
All reactions
This discussion was converted from issue #1984 on December 11, 2024 10:56.