diff --git a/dvc/scm/git/__init__.py b/dvc/scm/git/__init__.py
index dd3e1f314..62dfa5dbb 100644
--- a/dvc/scm/git/__init__.py
+++ b/dvc/scm/git/__init__.py
@@ -104,6 +104,16 @@ class Git(Base):
 
         return entry, gitignore
 
+    @staticmethod
+    def _ignored(entry, gitignore_path):
+        if os.path.exists(gitignore_path):
+            with open(gitignore_path, "r") as fobj:
+                ignore_list = fobj.readlines()
+            return any(
+                filter(lambda x: x.strip() == entry.strip(), ignore_list)
+            )
+        return False
+
     def ignore(self, path, in_curr_dir=False):
         base_dir = (
             os.path.realpath(os.curdir)
@@ -112,31 +122,32 @@ class Git(Base):
         )
         entry, gitignore = self._get_gitignore(path, base_dir)
 
-        ignore_list = []
-        if os.path.exists(gitignore):
-            with open(gitignore, "r") as f:
-                ignore_list = f.readlines()
-            if any(filter(lambda x: x.strip() == entry.strip(), ignore_list)):
-                return
+        if self._ignored(entry, gitignore):
+            return
 
         msg = "Adding '{}' to '{}'.".format(
             os.path.relpath(path), os.path.relpath(gitignore)
         )
         logger.info(msg)
 
-        self._add_entry_to_gitignore(entry, gitignore, ignore_list)
+        self._add_entry_to_gitignore(entry, gitignore)
 
         self.track_file(os.path.relpath(gitignore))
 
         self.ignored_paths.append(path)
 
     @staticmethod
-    def _add_entry_to_gitignore(entry, gitignore, ignore_list):
-        content = entry
-        if ignore_list:
-            content = "\n" + content
-        with open(gitignore, "a", encoding="utf-8") as fobj:
-            fobj.write(content)
+    def _add_entry_to_gitignore(entry, gitignore):
+        with open(gitignore, "a+", encoding="utf-8") as fobj:
+            fobj.seek(0, os.SEEK_END)
+            if fobj.tell() == 0:
+                # Empty file
+                prefix = ""
+            else:
+                fobj.seek(fobj.tell() - 1, os.SEEK_SET)
+                last = fobj.read(1)
+                prefix = "" if last == "\n" else "\n"
+            fobj.write("{}{}\n".format(prefix, entry))
 
     def ignore_remove(self, path):
         entry, gitignore = self._get_gitignore(path)

Newline in .gitignore
diff --git a/tests/func/test_scm.py b/tests/func/test_scm.py
index 885b9c613..8135f6606 100644
--- a/tests/func/test_scm.py
+++ b/tests/func/test_scm.py
@@ -2,6 +2,7 @@ from __future__ import unicode_literals
 
 import os
 
+import pytest
 from git import Repo
 
 from dvc.utils.compat import str  # noqa: F401
@@ -61,80 +62,133 @@ class TestSCMGitSubmodule(TestGitSubmodule):
         self.assertTrue("foo" in self.git.git.ls_files())
 
 
-class TestIgnore(TestGit):
-    def _count_gitignore(self):
+class TestIgnore(object):
+    @staticmethod
+    def _count_gitignore_entries(string):
         lines = get_gitignore_content()
-        return len([i for i in lines if i == "/" + self.FOO])
+        return len([i for i in lines if i == string])
 
-    def test_ignore(self):
-        git = Git(self._root_dir)
-        foo = os.path.join(self._root_dir, self.FOO)
+    def test_ignore(self, git, repo_dir):
+        git = Git(repo_dir._root_dir)
+        foo = os.path.join(repo_dir._root_dir, repo_dir.FOO)
+
+        target = "/" + repo_dir.FOO
 
         git.ignore(foo)
-        self.assertTrue(os.path.isfile(Git.GITIGNORE))
-        self.assertEqual(self._count_gitignore(), 1)
+        assert os.path.isfile(Git.GITIGNORE)
+        assert self._count_gitignore_entries(target) == 1
 
         git.ignore(foo)
-        self.assertEqual(self._count_gitignore(), 1)
+        assert os.path.isfile(Git.GITIGNORE)
+        assert self._count_gitignore_entries(target) == 1
 
         git.ignore_remove(foo)
-        self.assertEqual(self._count_gitignore(), 0)
-
-    def test_get_gitignore(self):
-        data_dir = os.path.join(self._root_dir, "file1")
-        entry, gitignore = Git(self._root_dir)._get_gitignore(data_dir)
-        self.assertEqual(entry, "/file1")
-        self.assertEqual(
-            gitignore, os.path.join(self._root_dir, Git.GITIGNORE)
-        )
+        assert self._count_gitignore_entries(target) == 0
 
-        data_dir = os.path.join(self._root_dir, "dir")
-        entry, gitignore = Git(self._root_dir)._get_gitignore(data_dir)
-        self.assertEqual(entry, "/dir")
-        self.assertEqual(
-            gitignore, os.path.join(self._root_dir, Git.GITIGNORE)
-        )
+    def test_get_gitignore(self, git, repo_dir):
+        data_dir = os.path.join(repo_dir._root_dir, "file1")
+        entry, gitignore = Git(repo_dir._root_dir)._get_gitignore(data_dir)
+        assert entry == "/file1"
+        assert gitignore == os.path.join(repo_dir._root_dir, Git.GITIGNORE)
 
-    def test_get_gitignore_subdir(self):
-        data_dir = os.path.join(self._root_dir, os.path.join("dir1", "file1"))
-        entry, gitignore = Git(self._root_dir)._get_gitignore(data_dir)
-        self.assertEqual(entry, "/file1")
-        self.assertEqual(
-            gitignore, os.path.join(self._root_dir, "dir1", Git.GITIGNORE)
+        data_dir = os.path.join(repo_dir._root_dir, "dir")
+        entry, gitignore = Git(repo_dir._root_dir)._get_gitignore(data_dir)
+
+        assert entry == "/dir"
+        assert gitignore == os.path.join(repo_dir._root_dir, Git.GITIGNORE)
+
+    def test_get_gitignore_subdir(self, git, repo_dir):
+        data_dir = os.path.join(
+            repo_dir._root_dir, os.path.join("dir1", "file1")
+        )
+        entry, gitignore = Git(repo_dir._root_dir)._get_gitignore(data_dir)
+        assert entry == "/file1"
+        assert gitignore == os.path.join(
+            repo_dir._root_dir, "dir1", Git.GITIGNORE
         )
 
-        data_dir = os.path.join(self._root_dir, os.path.join("dir1", "dir2"))
-        entry, gitignore = Git(self._root_dir)._get_gitignore(data_dir)
-        self.assertEqual(entry, "/dir2")
-        self.assertEqual(
-            gitignore, os.path.join(self._root_dir, "dir1", Git.GITIGNORE)
+        data_dir = os.path.join(
+            repo_dir._root_dir, os.path.join("dir1", "dir2")
+        )
+        entry, gitignore = Git(repo_dir._root_dir)._get_gitignore(data_dir)
+        assert entry == "/dir2"
+        assert gitignore == os.path.join(
+            repo_dir._root_dir, "dir1", Git.GITIGNORE
         )
 
-    def test_get_gitignore_ignorefile_dir(self):
-        git = Git(self._root_dir)
+    def test_get_gitignore_ignorefile_dir(self, git, repo_dir):
+        git = Git(repo_dir._root_dir)
 
         file_double_dir = os.path.join("dir1", "dir2", "file1")
-        data_dir1 = os.path.join(self._root_dir, file_double_dir)
+        data_dir1 = os.path.join(repo_dir._root_dir, file_double_dir)
         dir1_real1 = os.path.realpath("dir1")
         entry, gitignore = git._get_gitignore(data_dir1, dir1_real1)
-        self.assertEqual(entry, "/dir2/file1")
-        gitignore1 = os.path.join(self._root_dir, "dir1", Git.GITIGNORE)
-        self.assertEqual(gitignore, gitignore1)
+        assert entry == "/dir2/file1"
+        gitignore1 = os.path.join(repo_dir._root_dir, "dir1", Git.GITIGNORE)
+        assert gitignore == gitignore1
 
         triple_dir = os.path.join("dir1", "dir2", "dir3")
-        data_dir2 = os.path.join(self._root_dir, triple_dir)
+        data_dir2 = os.path.join(repo_dir._root_dir, triple_dir)
         dir1_real2 = os.path.realpath("dir1")
         entry, gitignore = git._get_gitignore(data_dir2, dir1_real2)
-        self.assertEqual(entry, "/dir2/dir3")
-        gitignore2 = os.path.join(self._root_dir, "dir1", Git.GITIGNORE)
-        self.assertEqual(gitignore, gitignore2)
+        assert entry == "/dir2/dir3"
+        gitignore2 = os.path.join(repo_dir._root_dir, "dir1", Git.GITIGNORE)
+        assert gitignore == gitignore2
 
-    def test_get_gitignore_ignorefile_dir_upper_level(self):
-        git = Git(self._root_dir)
+    def test_get_gitignore_ignorefile_dir_upper_level(self, git, repo_dir):
+        git = Git(repo_dir._root_dir)
 
         file_double_dir = os.path.join("dir1", "dir2", "file1")
-        data_dir1 = os.path.join(self._root_dir, file_double_dir)
+        data_dir1 = os.path.join(repo_dir._root_dir, file_double_dir)
         ignore_file_dir = os.path.realpath(os.path.join("aa", "bb"))
 
-        with self.assertRaises(FileNotInTargetSubdirError):
+        with pytest.raises(FileNotInTargetSubdirError):
             git._get_gitignore(data_dir1, ignore_file_dir)
+
+    def test_gitignore_should_end_with_newline(self, git, repo_dir):
+        git = Git(repo_dir._root_dir)
+
+        foo = os.path.join(repo_dir._root_dir, repo_dir.FOO)
+        bar = os.path.join(repo_dir._root_dir, repo_dir.BAR)
+        gitignore = os.path.join(repo_dir._root_dir, Git.GITIGNORE)
+
+        git.ignore(foo)
+
+        with open(gitignore, "r") as fobj:
+            last = fobj.readlines()[-1]
+
+        assert last.endswith("\n")
+
+        git.ignore(bar)
+
+        with open(gitignore, "r") as fobj:
+            last = fobj.readlines()[-1]
+
+        assert last.endswith("\n")
+
+    def test_gitignore_should_append_newline_to_gitignore(self, git, repo_dir):
+        git = Git(repo_dir._root_dir)
+
+        foo_ignore_pattern = "/foo"
+        bar_ignore_pattern = "/bar"
+        bar_path = os.path.join(repo_dir._root_dir, repo_dir.BAR)
+        gitignore = os.path.join(repo_dir._root_dir, Git.GITIGNORE)
+
+        with open(gitignore, "w") as fobj:
+            fobj.write(foo_ignore_pattern)
+
+        with open(gitignore, "r") as fobj:
+            last = fobj.readlines()[-1]
+        assert not last.endswith("\n")
+
+        git.ignore(bar_path)
+
+        with open(gitignore, "r") as fobj:
+            lines = list(fobj.readlines())
+
+        assert len(lines) == 2
+        for l in lines:
+            assert l.endswith("\n")
+
+        assert lines[0].strip() == foo_ignore_pattern
+        assert lines[1].strip() == bar_ignore_pattern

pip install -e .[all]
parse_log_pytest
pytest
pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio pytest
apt-get update apt-get install -y gcc pip install -e .[tests]
3.7
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
aliyun-python-sdk-core==2.16.0
aliyun-python-sdk-core-v3==2.13.33
aliyun-python-sdk-kms==2.16.5
altgraph==0.17.4
appdirs==1.4.4
asciimatics==1.14.0
attrs @ file:///croot/attrs_1668696182826/work
autocommand==2.2.2
awscli==1.31.13
azure-common==1.1.28
azure-nspkg==3.0.2
azure-storage-blob==1.3.0
azure-storage-common==1.3.0
azure-storage-nspkg==3.1.0
bcrypt==4.2.1
black==19.3b0
boto==2.49.0
boto3==1.9.115
botocore==1.12.253
cachetools==5.5.2
certifi @ file:///croot/certifi_1671487769961/work/certifi
cffi==1.15.1
charset-normalizer==3.4.1
click==8.1.8
collective.checkdocs==0.2
colorama==0.4.4
configobj==5.0.9
configparser==5.3.0
coverage==7.2.7
crcmod==1.7
cryptography==44.0.2
distro==1.9.0
docutils==0.15.2
dulwich==0.22.1
-e git+https://github.com/iterative/dvc.git@dd7876e72f0317209144318c0639f8c1e8b00199#egg=dvc
execnet==2.0.2
flake8==5.0.4
flake8-docstrings==1.7.0
flaky==3.8.1
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
funcy==2.0
future==1.0.0
gitdb==4.0.12
GitPython==3.1.44
google-api-core==1.34.1
google-auth==2.38.0
google-cloud-core==0.28.1
google-cloud-storage==1.13.0
google-compute-engine==2.8.13
google-crc32c==1.5.0
google-resumable-media==2.7.2
googleapis-common-protos==1.69.2
grandalf==0.6
humanize==4.6.0
idna==3.10
importlib-metadata==4.2.0
importlib-resources==5.12.0
inflect==6.0.5
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
jaraco.classes==3.2.3
jaraco.collections==4.2.0
jaraco.context==4.3.0
jaraco.functools==3.7.0
jaraco.structures==2.1.0
jaraco.text==3.11.1
jaraco.ui==2.3.0
jaraco.windows==3.9.2
jmespath==0.10.0
jsonpath-ng==1.7.0
macholib==1.16.3
mccabe==0.7.0
mock==5.2.0
mock-ssh-server==0.9.1
more-itertools==9.1.0
nanotime==0.5.2
networkx==2.6.3
oss2==2.6.1
packaging @ file:///croot/packaging_1671697413597/work
paramiko==3.5.1
path==16.6.0
path.py==12.5.0
pefile==2024.8.26
Pillow==9.5.0
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
ply==3.11
protobuf==3.20.3
psutil==5.6.2
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyasn1==0.5.1
pyasn1-modules==0.3.0
pycodestyle==2.9.1
pycparser==2.21
pycryptodome==3.22.0
pydantic==1.10.21
pydocstyle==6.3.0
pydot==2.0.0
pyfiglet==0.8.post1
pyflakes==2.5.0
Pygments==2.17.2
PyInstaller==3.4
PyNaCl==1.5.0
pyparsing==3.1.4
pytest==7.1.2
pytest-asyncio==0.21.2
pytest-cov==4.1.0
pytest-mock==3.11.1
pytest-timeout==2.3.1
pytest-xdist==3.5.0
python-dateutil==2.9.0.post0
PyYAML==6.0.1
requests==2.31.0
rsa==4.7.2
ruamel.yaml==0.18.10
ruamel.yaml.clib==0.2.8
s3transfer==0.2.1
schema==0.7.7
six==1.17.0
smmap==5.0.2
snowballstemmer==2.2.0
toml==0.10.2
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
treelib==1.7.1
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
urllib3==1.25.11
wcwidth==0.2.13
xmltodict==0.14.2
zc.lockfile==3.0.post1
zipp @ file:///croot/zipp_1672387121353/work

name: dvc
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - attrs=22.1.0=py37h06a4308_0
  - ca-certificates=2025.2.25=h06a4308_0
  - certifi=2022.12.7=py37h06a4308_0
  - flit-core=3.6.0=pyhd3eb1b0_0
  - importlib_metadata=4.11.3=hd3eb1b0_0
  - iniconfig=1.1.1=pyhd3eb1b0_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.4.4=h6a678d5_1
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - ncurses=6.4=h6a678d5_0
  - openssl=1.1.1w=h7f8727e_0
  - packaging=22.0=py37h06a4308_0
  - pip=22.3.1=py37h06a4308_0
  - pluggy=1.0.0=py37h06a4308_1
  - py=1.11.0=pyhd3eb1b0_0
  - pytest=7.1.2=py37h06a4308_0
  - python=3.7.16=h7a1cb2a_0
  - readline=8.2=h5eee18b_0
  - setuptools=65.6.3=py37h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - tomli=2.0.1=py37h06a4308_0
  - typing_extensions=4.4.0=py37h06a4308_0
  - wheel=0.38.4=py37h06a4308_0
  - xz=5.6.4=h5eee18b_1
  - zipp=3.11.0=py37h06a4308_0
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - aliyun-python-sdk-core==2.16.0
      - aliyun-python-sdk-core-v3==2.13.33
      - aliyun-python-sdk-kms==2.16.5
      - altgraph==0.17.4
      - appdirs==1.4.4
      - asciimatics==1.14.0
      - autocommand==2.2.2
      - awscli==1.31.13
      - azure-common==1.1.28
      - azure-nspkg==3.0.2
      - azure-storage-blob==1.3.0
      - azure-storage-common==1.3.0
      - azure-storage-nspkg==3.1.0
      - bcrypt==4.2.1
      - black==19.3b0
      - boto==2.49.0
      - boto3==1.9.115
      - botocore==1.12.253
      - cachetools==5.5.2
      - cffi==1.15.1
      - charset-normalizer==3.4.1
      - click==8.1.8
      - collective-checkdocs==0.2
      - colorama==0.4.4
      - configobj==5.0.9
      - configparser==5.3.0
      - coverage==7.2.7
      - crcmod==1.7
      - cryptography==44.0.2
      - distro==1.9.0
      - docutils==0.15.2
      - dulwich==0.22.1
      - dvc==0.41.3
      - execnet==2.0.2
      - flake8==5.0.4
      - flake8-docstrings==1.7.0
      - flaky==3.8.1
      - funcy==2.0
      - future==1.0.0
      - gitdb==4.0.12
      - gitpython==3.1.44
      - google-api-core==1.34.1
      - google-auth==2.38.0
      - google-cloud-core==0.28.1
      - google-cloud-storage==1.13.0
      - google-compute-engine==2.8.13
      - google-crc32c==1.5.0
      - google-resumable-media==2.7.2
      - googleapis-common-protos==1.69.2
      - grandalf==0.6
      - humanize==4.6.0
      - idna==3.10
      - importlib-metadata==4.2.0
      - importlib-resources==5.12.0
      - inflect==6.0.5
      - jaraco-classes==3.2.3
      - jaraco-collections==4.2.0
      - jaraco-context==4.3.0
      - jaraco-functools==3.7.0
      - jaraco-structures==2.1.0
      - jaraco-text==3.11.1
      - jaraco-ui==2.3.0
      - jaraco-windows==3.9.2
      - jmespath==0.10.0
      - jsonpath-ng==1.7.0
      - macholib==1.16.3
      - mccabe==0.7.0
      - mock==5.2.0
      - mock-ssh-server==0.9.1
      - more-itertools==9.1.0
      - nanotime==0.5.2
      - networkx==2.6.3
      - oss2==2.6.1
      - paramiko==3.5.1
      - path==16.6.0
      - path-py==12.5.0
      - pefile==2024.8.26
      - pillow==9.5.0
      - ply==3.11
      - protobuf==3.20.3
      - psutil==5.6.2
      - pyasn1==0.5.1
      - pyasn1-modules==0.3.0
      - pycodestyle==2.9.1
      - pycparser==2.21
      - pycryptodome==3.22.0
      - pydantic==1.10.21
      - pydocstyle==6.3.0
      - pydot==2.0.0
      - pyfiglet==0.8.post1
      - pyflakes==2.5.0
      - pygments==2.17.2
      - pyinstaller==3.4
      - pynacl==1.5.0
      - pyparsing==3.1.4
      - pytest-asyncio==0.21.2
      - pytest-cov==4.1.0
      - pytest-mock==3.11.1
      - pytest-timeout==2.3.1
      - pytest-xdist==3.5.0
      - python-dateutil==2.9.0.post0
      - pyyaml==6.0.1
      - requests==2.31.0
      - rsa==4.7.2
      - ruamel-yaml==0.18.10
      - ruamel-yaml-clib==0.2.8
      - s3transfer==0.2.1
      - schema==0.7.7
      - six==1.17.0
      - smmap==5.0.2
      - snowballstemmer==2.2.0
      - toml==0.10.2
      - treelib==1.7.1
      - urllib3==1.25.11
      - wcwidth==0.2.13
      - xmltodict==0.14.2
      - zc-lockfile==3.0.post1
prefix: /opt/conda/envs/dvc

tests/func/test_scm.py::TestIgnore::test_gitignore_should_end_with_newline tests/func/test_scm.py::TestIgnore::test_gitignore_should_append_newline_to_gitignore
tests/func/test_scm.py::TestSCM::test_git tests/func/test_scm.py::TestSCM::test_none tests/func/test_scm.py::TestSCMGit::test_commit tests/func/test_scm.py::TestSCMGit::test_is_repo tests/func/test_scm.py::TestSCMGit::test_is_tracked tests/func/test_scm.py::TestSCMGitSubmodule::test_commit_in_submodule tests/func/test_scm.py::TestSCMGitSubmodule::test_git_submodule tests/func/test_scm.py::TestSCMGitSubmodule::test_is_submodule tests/func/test_scm.py::TestIgnore::test_ignore tests/func/test_scm.py::TestIgnore::test_get_gitignore tests/func/test_scm.py::TestIgnore::test_get_gitignore_subdir tests/func/test_scm.py::TestIgnore::test_get_gitignore_ignorefile_dir tests/func/test_scm.py::TestIgnore::test_get_gitignore_ignorefile_dir_upper_level
dvc/scm/git/__init__.py
dvc/scm/git/__init__.py