Python os.removedirs() Examples

The following are 30 code examples of os.removedirs(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: misc.py    From pex with Apache License 2.0 6 votes vote down vote up
def renames(old, new):
    # type: (str, str) -> None
    """Like os.renames(), but handles renaming across devices."""
    # Implementation borrowed from os.renames().
    head, tail = os.path.split(new)
    if head and tail and not os.path.exists(head):
        os.makedirs(head)

    shutil.move(old, new)

    head, tail = os.path.split(old)
    if head and tail:
        try:
            os.removedirs(head)
        except OSError:
            pass 
Example #2
Source File: misc.py    From Building-Recommendation-Systems-with-Python with MIT License 6 votes vote down vote up
def renames(old, new):
    # type: (str, str) -> None
    """Like os.renames(), but handles renaming across devices."""
    # Implementation borrowed from os.renames().
    head, tail = os.path.split(new)
    if head and tail and not os.path.exists(head):
        os.makedirs(head)

    shutil.move(old, new)

    head, tail = os.path.split(old)
    if head and tail:
        try:
            os.removedirs(head)
        except OSError:
            pass 
Example #3
Source File: test_self.py    From python-netsurv with MIT License 6 votes vote down vote up
def test_parseable_file_path(self):
        file_name = "test_target.py"
        fake_path = HERE + os.getcwd()
        module = join(fake_path, file_name)

        try:
            # create module under directories which have the same name as reporter.path_strip_prefix
            # e.g. /src/some/path/src/test_target.py when reporter.path_strip_prefix = /src/
            os.makedirs(fake_path)
            with open(module, "w") as test_target:
                test_target.write("a,b = object()")

            self._test_output(
                [module, "--output-format=parseable"],
                expected_output=join(os.getcwd(), file_name),
            )
        finally:
            os.remove(module)
            os.removedirs(fake_path) 
Example #4
Source File: test_self.py    From python-netsurv with MIT License 6 votes vote down vote up
def test_parseable_file_path(self):
        file_name = "test_target.py"
        fake_path = HERE + os.getcwd()
        module = join(fake_path, file_name)

        try:
            # create module under directories which have the same name as reporter.path_strip_prefix
            # e.g. /src/some/path/src/test_target.py when reporter.path_strip_prefix = /src/
            os.makedirs(fake_path)
            with open(module, "w") as test_target:
                test_target.write("a,b = object()")

            self._test_output(
                [module, "--output-format=parseable"],
                expected_output=join(os.getcwd(), file_name),
            )
        finally:
            os.remove(module)
            os.removedirs(fake_path) 
Example #5
Source File: misc.py    From scylla with Apache License 2.0 6 votes vote down vote up
def renames(old, new):
    # type: (str, str) -> None
    """Like os.renames(), but handles renaming across devices."""
    # Implementation borrowed from os.renames().
    head, tail = os.path.split(new)
    if head and tail and not os.path.exists(head):
        os.makedirs(head)

    shutil.move(old, new)

    head, tail = os.path.split(old)
    if head and tail:
        try:
            os.removedirs(head)
        except OSError:
            pass 
Example #6
Source File: misc.py    From Building-Recommendation-Systems-with-Python with MIT License 6 votes vote down vote up
def renames(old, new):
    # type: (str, str) -> None
    """Like os.renames(), but handles renaming across devices."""
    # Implementation borrowed from os.renames().
    head, tail = os.path.split(new)
    if head and tail and not os.path.exists(head):
        os.makedirs(head)

    shutil.move(old, new)

    head, tail = os.path.split(old)
    if head and tail:
        try:
            os.removedirs(head)
        except OSError:
            pass 
Example #7
Source File: test_vyper.py    From vyper with MIT License 6 votes vote down vote up
def _init_dirs(self):
        test_dirs = ["a a", "b", "D_"]
        config = "improbable"
        root = tempfile.mkdtemp()

        def cleanup():
            try:
                os.removedirs(root)
            except (FileNotFoundError, OSError):
                pass

        os.chdir(root)

        for dir_ in test_dirs:
            os.mkdir(dir_, 0o0750)

            f = "{0}.toml".format(config)
            flags = os.O_WRONLY | os.O_CREAT
            rel_path = "{0}/{1}".format(dir_, f)
            abs_file_path = os.path.join(root, rel_path)
            with os.fdopen(os.open(abs_file_path, flags, 0o0640), "w") as fp:
                fp.write('key = "value is {0}"\n'.format(dir_))

        return root, config, cleanup 
Example #8
Source File: test_cache.py    From yatsm with MIT License 6 votes vote down vote up
def test_test_cache(mkdir_permissions):
    # Test when cache dir exists already
    path = mkdir_permissions(read=False, write=False)
    assert (False, False) == cache.test_cache(dict(cache_line_dir=path))

    path = mkdir_permissions(read=False, write=True)
    assert (False, True) == cache.test_cache(dict(cache_line_dir=path))

    path = mkdir_permissions(read=True, write=False)
    assert (True, False) == cache.test_cache(dict(cache_line_dir=path))

    path = mkdir_permissions(read=True, write=True)
    assert (True, True) == cache.test_cache(dict(cache_line_dir=path))

    # Test when cache dir doesn't exist
    tmp = os.path.join(tempfile.tempdir,
                       next(tempfile._get_candidate_names()) + '_yatsm')
    read_write = cache.test_cache(dict(cache_line_dir=tmp))
    os.removedirs(tmp)

    assert (True, True) == read_write 
Example #9
Source File: conftest.py    From yatsm with MIT License 6 votes vote down vote up
def mkdir_permissions(request):
    """ Fixture for creating dir with specific read/write permissions """
    def make_mkdir(read=False, write=False):
        if read and write:
            mode = 0o755
        elif read and not write:
            mode = 0o555
        elif not read and write:
            mode = 0o333
        elif not read and not write:
            mode = 0o000

        path = mkdtemp()
        os.chmod(path, mode)

        def fin():
            os.chmod(path, 0o755)
            os.removedirs(path)
        request.addfinalizer(fin)

        return path

    return make_mkdir 
Example #10
Source File: systrace.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def RemoveAllStalePycFiles(base_dir):
  """Scan directories for old .pyc files without a .py file and delete them."""
  for dirname, _, filenames in os.walk(base_dir):
    if '.git' in dirname:
      continue
    for filename in filenames:
      root, ext = os.path.splitext(filename)
      if ext != '.pyc':
        continue

      pyc_path = os.path.join(dirname, filename)
      py_path = os.path.join(dirname, root + '.py')

      try:
        if not os.path.exists(py_path):
          os.remove(pyc_path)
      except OSError:
        # Wrap OS calls in try/except in case another process touched this file.
        pass

    try:
      os.removedirs(dirname)
    except OSError:
      # Wrap OS calls in try/except in case another process touched this dir.
      pass 
Example #11
Source File: util.py    From QQZoneMood with MIT License 6 votes vote down vote up
def do_clear_data_by_user(QQ, conn):
    DATA_DIR_KEY = BASE_DIR + QQ + '/'
    WEB_IMAGE_PATH_DIR = WEB_IMAGE_PATH + QQ + '/'
    if os.path.exists(DATA_DIR_KEY):
        # 删除有QQ号的所有key
        # 该方法在docker中无法使用,因为该容器内无redis-cli
        # delete_cmd = "redis-cli KEYS \"*" + QQ + "*\"|xargs redis-cli DEL"
        # print(delete_cmd)
        # os.system(delete_cmd)
        # 删除 该路径下所有文件
        os.system("rm -rf " + DATA_DIR_KEY)
        os.system("rm -rf " + WEB_IMAGE_PATH_DIR)
        conn.hdel(USER_MAP_KEY, QQ)
        conn.lrem(WAITING_USER_LIST, 0, QQ)
        # redis的del不支持正则表达式,因此只能循环删除
        all_keys = conn.keys("*" + QQ + "*")
        print()
        for key in all_keys:
            conn.delete(key)
        # os.removedirs(os.path.join(BASE_DIR, QQ))
        finish = 1
    else:
        finish = 2
    return finish 
Example #12
Source File: dataController.py    From QQZoneMood with MIT License 6 votes vote down vote up
def do_clear_data_by_user(QQ, conn):
    DATA_DIR_KEY = BASE_DIR + QQ + '/'
    WEB_IMAGE_PATH_DIR = WEB_IMAGE_PATH + QQ + '/'
    if os.path.exists(DATA_DIR_KEY):
        # 删除有QQ号的所有key
        # 该方法在docker中无法使用,因为该容器内无redis-cli
        # delete_cmd = "redis-cli KEYS \"*" + QQ + "*\"|xargs redis-cli DEL"
        # print(delete_cmd)
        # os.system(delete_cmd)
        # 删除 该路径下所有文件
        os.system("rm -rf " + DATA_DIR_KEY)
        os.system("rm -rf " + WEB_IMAGE_PATH_DIR)
        conn.hdel(USER_MAP_KEY, QQ)
        conn.lrem(WAITING_USER_LIST, 0, QQ)
        # redis的del不支持正则表达式,因此只能循环删除
        all_keys = conn.keys("*" + QQ + "*")
        print()
        for key in all_keys:
            conn.delete(key)
        # os.removedirs(os.path.join(BASE_DIR, QQ))
        finish = 1
    else:
        finish = 2
    return finish 
Example #13
Source File: systrace.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def RemoveAllStalePycFiles(base_dir):
  """Scan directories for old .pyc files without a .py file and delete them."""
  for dirname, _, filenames in os.walk(base_dir):
    if '.git' in dirname:
      continue
    for filename in filenames:
      root, ext = os.path.splitext(filename)
      if ext != '.pyc':
        continue

      pyc_path = os.path.join(dirname, filename)
      py_path = os.path.join(dirname, root + '.py')

      try:
        if not os.path.exists(py_path):
          os.remove(pyc_path)
      except OSError:
        # Wrap OS calls in try/except in case another process touched this file.
        pass

    try:
      os.removedirs(dirname)
    except OSError:
      # Wrap OS calls in try/except in case another process touched this dir.
      pass 
Example #14
Source File: ofsorter.py    From OnlyFans with GNU General Public License v3.0 6 votes vote down vote up
def sorter(user_directory, api_type, location, metadata):
    legacy_directory = os.path.join(user_directory, api_type, location)
    if not os.path.isdir(legacy_directory):
        return
    legacy_files = os.listdir(legacy_directory)
    metadata_directory = os.path.join(
        user_directory, "Metadata", api_type+".json")
    results = list(chain(*metadata["valid"]))
    for result in results:
        legacy_filepath = os.path.join(legacy_directory, result["filename"])
        filepath = os.path.join(result["directory"], result["filename"])
        if result["filename"] in legacy_files:
            if os.path.isfile(filepath):
                same_file = filecmp.cmp(
                    legacy_filepath, filepath, shallow=False)
                if same_file:
                    os.remove(filepath)
                else:
                    os.remove(legacy_filepath)
                    continue
            shutil.move(legacy_filepath, filepath)
    if not os.listdir(legacy_directory):
        os.removedirs(legacy_directory) 
Example #15
Source File: systrace.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def RemoveAllStalePycFiles(base_dir):
  """Scan directories for old .pyc files without a .py file and delete them."""
  for dirname, _, filenames in os.walk(base_dir):
    if '.git' in dirname:
      continue
    for filename in filenames:
      root, ext = os.path.splitext(filename)
      if ext != '.pyc':
        continue

      pyc_path = os.path.join(dirname, filename)
      py_path = os.path.join(dirname, root + '.py')

      try:
        if not os.path.exists(py_path):
          os.remove(pyc_path)
      except OSError:
        # Wrap OS calls in try/except in case another process touched this file.
        pass

    try:
      os.removedirs(dirname)
    except OSError:
      # Wrap OS calls in try/except in case another process touched this dir.
      pass 
Example #16
Source File: generic.py    From pyiron with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def delete_output_files_jobs(self, recursive=False):
        """
        Delete the output files of all finished jobs in the current project and in all subprojects if recursive=True is
        selected.

        Args:
            recursive (bool): [True/False] delete the output files of all jobs in all subprojects - default=False
        """
        for job_id in self.get_job_ids(recursive=recursive):
            job = self.inspect(job_id)
            if job.status == "finished":
                for file in job.list_files():
                    fullname = os.path.join(job.working_directory, file)
                    if os.path.isfile(fullname) and ".h5" not in fullname:
                        os.remove(fullname)
                    elif os.path.isdir(fullname):
                        os.removedirs(fullname) 
Example #17
Source File: misc.py    From pipenv with MIT License 6 votes vote down vote up
def renames(old, new):
    # type: (str, str) -> None
    """Like os.renames(), but handles renaming across devices."""
    # Implementation borrowed from os.renames().
    head, tail = os.path.split(new)
    if head and tail and not os.path.exists(head):
        os.makedirs(head)

    shutil.move(old, new)

    head, tail = os.path.split(old)
    if head and tail:
        try:
            os.removedirs(head)
        except OSError:
            pass 
Example #18
Source File: misc.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def renames(old, new):
    # type: (str, str) -> None
    """Like os.renames(), but handles renaming across devices."""
    # Implementation borrowed from os.renames().
    head, tail = os.path.split(new)
    if head and tail and not os.path.exists(head):
        os.makedirs(head)

    shutil.move(old, new)

    head, tail = os.path.split(old)
    if head and tail:
        try:
            os.removedirs(head)
        except OSError:
            pass 
Example #19
Source File: misc.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def renames(old, new):
    # type: (str, str) -> None
    """Like os.renames(), but handles renaming across devices."""
    # Implementation borrowed from os.renames().
    head, tail = os.path.split(new)
    if head and tail and not os.path.exists(head):
        os.makedirs(head)

    shutil.move(old, new)

    head, tail = os.path.split(old)
    if head and tail:
        try:
            os.removedirs(head)
        except OSError:
            pass 
Example #20
Source File: misc.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def renames(old, new):
    # type: (str, str) -> None
    """Like os.renames(), but handles renaming across devices."""
    # Implementation borrowed from os.renames().
    head, tail = os.path.split(new)
    if head and tail and not os.path.exists(head):
        os.makedirs(head)

    shutil.move(old, new)

    head, tail = os.path.split(old)
    if head and tail:
        try:
            os.removedirs(head)
        except OSError:
            pass 
Example #21
Source File: __init__.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def renames(old, new):
    """Like os.renames(), but handles renaming across devices."""
    # Implementation borrowed from os.renames().
    head, tail = os.path.split(new)
    if head and tail and not os.path.exists(head):
        os.makedirs(head)

    shutil.move(old, new)

    head, tail = os.path.split(old)
    if head and tail:
        try:
            os.removedirs(head)
        except OSError:
            pass 
Example #22
Source File: document_test.py    From Gap with Apache License 2.0 5 votes vote down vote up
def test_013(self):
        """ Document constructor - create page directory """
        document = Document("files/4page.pdf", "tests2")
        self.assertTrue(os.path.isdir("tests2"))
        for i in range(1,5):
            os.remove("tests2/4page" + str(i) + ".pdf")
            os.remove("tests2/4page" + str(i) + ".txt")
            os.remove("tests2/4page" + str(i) + ".json")
        os.removedirs("tests2") 
Example #23
Source File: test_get_frontend_version.py    From integration with MIT License 5 votes vote down vote up
def temp_cleanup(tmpdir):
    hacsdir = f"{tmpdir.dirname}/custom_components/hacs"
    manifestfile = f"{hacsdir}/manifest.json"
    if os.path.exists(manifestfile):
        os.remove(manifestfile)
    if os.path.exists(hacsdir):
        os.removedirs(hacsdir) 
Example #24
Source File: test_constrains.py    From integration with MIT License 5 votes vote down vote up
def temp_cleanup(tmpdir):
    manifest = f"{tmpdir.dirname}/custom_components/hacs/manifest.json"
    translations_dir = f"{tmpdir.dirname}/custom_components/hacs/translations"
    custom_updater1 = f"{tmpdir.dirname}/custom_components/custom_updater/__init__.py"
    custom_updater2 = f"{tmpdir.dirname}/custom_components/custom_updater.py"

    if os.path.exists(manifest):
        os.remove(manifest)
    if os.path.exists(translations_dir):
        os.removedirs(translations_dir)
    if os.path.exists(custom_updater1):
        os.remove(custom_updater1)
    if os.path.exists(custom_updater2):
        os.remove(custom_updater2) 
Example #25
Source File: test_read_hacs_manifest.py    From integration with MIT License 5 votes vote down vote up
def temp_cleanup(tmpdir):
    hacsdir = f"{tmpdir.dirname}/custom_components/hacs"
    manifestfile = f"{hacsdir}/manifest.json"
    if os.path.exists(manifestfile):
        os.remove(manifestfile)
    if os.path.exists(hacsdir):
        os.removedirs(hacsdir) 
Example #26
Source File: delete_build.py    From tools_python with Apache License 2.0 5 votes vote down vote up
def remove_dir(dir_path):
    print("删除文件夹的目录是:"+dir_path)

    # 如果是空文件夹
    if not os.listdir(dir_path):
       os.removedirs(dir_path)

    for root, dirs, files in os.walk(dir_path, topdown=False):
        for name in files:
            os.remove(os.path.join(root, name))
        for name in dirs:
            os.rmdir(os.path.join(root, name)) 
Example #27
Source File: _url.py    From pytablereader with MIT License 5 votes vote down vote up
def __del__(self):
        if typepy.is_null_string(self.__temp_dir_path):
            return

        os.removedirs(self.__temp_dir_path)
        self.__temp_dir_path = None 
Example #28
Source File: generic.py    From pyiron with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def remove(self, enable=False, enforce=False):
        """
        Delete all the whole project including all jobs in the project and its subprojects

        Args:
            enforce (bool): [True/False] delete jobs even though they are used in other projects - default=False
            enable (bool): [True/False] enable this command.
        """
        if enable is not True:
            raise ValueError(
                "To prevent users from accidentally deleting files - enable has to be set to True."
            )
        if not self.view_mode:
            for sub_project_name in self.list_groups():
                if "_hdf5" not in sub_project_name:
                    sub_project = self.open(sub_project_name)
                    sub_project.remove(enable=enable, enforce=enforce)
            self.remove_jobs(recursive=True)
            for file in self.list_files():
                os.remove(os.path.join(self.path, file))
            if enforce:
                print("remove directory: {}".format(self.path))
                shutil.rmtree(self.path, ignore_errors=True)
            else:
                self.parent_group.removedirs(self.base_name)
        else:
            raise EnvironmentError("copy_to: is not available in Viewermode !") 
Example #29
Source File: clean.py    From run_idat with GNU General Public License v3.0 5 votes vote down vote up
def deldir(d):
    if (not os.path.exists(d)):
        return False
    else:
        for k in getfilelist(d):
            os.remove(k)
        # os.removedirs(d)
        return True 
Example #30
Source File: path.py    From pyiron with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def removedirs(self, project_name=None):
        """
        equivalent to os.removedirs  -> remove empty dirs

        Args:
            project_name (str): relative path to the project folder to be deleted

        """
        try:
            if project_name:
                os.removedirs(os.path.join(self.path, project_name))
            else:
                os.removedirs(os.path.join(self.path))
        except OSError:
            pass