0

When the file I'm rewriting has the following content:

one
two
four

and I rewrite it to:

one
two
three
four

I expect the git diffto say that I've added a line with "three", but it says that I've removed everything in the first version and then added everything in the second version.

This is how I'm writing the file:

with open(file_path, 'w') as my_file:
    my_file.write(my_text)

What can I do to get the output I expect from git diff?

Benjamin
  • 437
  • 4
  • 9

1 Answers1

0

Why don't you try appending to the file. That will show the appropriate addition to you git diff. It opens the file in append mode instead of write mode which might help.

f = open(file_path, 'a+'):

f.write(your_text)

Other option in case you need to add the changes to the file in between lines, then use a f.writelines(values) to update the contents.

Anurag Reddy
  • 1,159
  • 11
  • 19
  • Sorry, my example was misleading! I've updated it now to show that I can't append to the file :) – Benjamin Mar 23 '20 at 16:42
  • 1
    Then did you try using `f.writelines()` and then use a `join`. This [link](https://stackoverflow.com/questions/10507230/insert-line-at-middle-of-file-with-python) might help you with that since you need to add at a certain index. And if this also does not solve your issue, then we will think of something else. – Anurag Reddy Mar 23 '20 at 16:48