Python os.removedirs() Examples

The following are code examples for showing how to use os.removedirs(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: ave   Author: sonyxperiadev   File: gtest.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def t05(w,h):
    pretty = '%s t5' % __file__
    print(pretty)

    result_path = w.make_tempdir()
    os.chmod(result_path, stat.S_IRUSR) # user read permission only
    try:
        h.run_gtest('some_target', result_path)
        print(
            'FAIL %s: expected error (not writable result directory): %s'
            % (pretty, temp_dir)
        )
        return False
    except Exception as e:
        if e.message != 'result_path not a writable directory: %s' % result_path:
            print('FAIL %s: wrong error message: %s' % (pretty, str(e)))
            return False
    finally:
        os.removedirs(result_path)
    return True

# successful execution of run_gtest(): check files on host, verfiy their
#   content and that traces from run removed from handset 
Example 2
Project: ave   Author: sonyxperiadev   File: gtest.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def t05(w,h):
    pretty = '%s t5' % __file__
    print(pretty)

    result_path = w.make_tempdir()
    os.chmod(result_path, stat.S_IRUSR) # user read permission only
    try:
        h.run_gtest('some_target', result_path)
        print(
            'FAIL %s: expected error (not writable result directory): %s'
            % (pretty, temp_dir)
        )
        return False
    except Exception as e:
        if e.message != 'result_path not a writable directory: %s' % result_path:
            print('FAIL %s: wrong error message: %s' % (pretty, str(e)))
            return False
    finally:
        os.removedirs(result_path)
    return True

# successful execution of run_gtest(): check files on host, verfiy their
#   content and that traces from run removed from handset 
Example 3
Project: nojs   Author: chrisdickinson   File: remove_stale_pyc_files.py    (license) View Source Project 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 '.svn' in dirname or '.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 4
Project: vyper   Author: admiralobvious   File: test_vyper.py    (license) View Source Project 6 votes vote down vote up
def _init_dirs(self):
        test_dirs = ['a a', 'b', 'c\c', '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 5
Project: sudokuextract   Author: hbldh   File: test_se.py    (license) View Source Project 6 votes vote down vote up
def test_se_tardata_sudokus(file_path_base):
    try:
        image_file_name = file_path_base + '.jpg'
        image = load_image(image_file_name)
    except:
        image_file_name = file_path_base + '.png'
        image = load_image(image_file_name)
    with open(file_path_base + '.txt', 'rt') as f:
        correct_parsing = f.read().strip()

    predictions, sudoku, subimage = extract_sudoku(image, classifier(), force=True)
    parsed_sudoku = predictions_to_suduko_string(predictions, oneliner=False)
    if parsed_sudoku != correct_parsing:
        predictions, sudoku, subimage = extract_sudoku(image.rotate(-90), classifier(), force=True)
        parsed_sudoku = predictions_to_suduko_string(predictions, oneliner=False)
    assert parsed_sudoku == correct_parsing


    try:
        os.remove(image_file_name)
        os.remove(file_path_base + '.txt')
        print("Deleted temporary test dir.")
        os.removedirs(os.path.dirname(file_path_base))
    except:
        pass 
Example 6
Project: sahriswiki   Author: prologic   File: storage.py    (license) View Source Project 6 votes vote down vote up
def delete_page(self, title, author=u'', comment=u''):
        """
        Remove empty directories after deleting a page.

        Note that Mercurial doesn't track directories, so we don't have to
        commit after removing empty directories.
        """

        super(WikiSubdirectoryStorage, self).delete_page(title, author, comment)
        file_path = self._file_path(title)
        self._check_path(file_path)
        dir_path = os.path.dirname(file_path)
        try:
            os.removedirs(dir_path)
        except OSError, e:
            pass # Ignore possibly OSError (39) Directory not empty errors. 
Example 7
Project: DawnlightSearch   Author: chg-hou   File: DawnlightSearch_main.py    (license) View Source Project 6 votes vote down vote up
def on_tableview_context_menu_delete(self):
        reply = QMessageBox.question(self, translate('message','Message'),
                                     translate('message',"Are you sure to DELETE?"), QMessageBox.Yes |
                                     QMessageBox.No, QMessageBox.No)

        if reply == QMessageBox.Yes:
            self.statusBar.showMessage(translate('statusbar',"Deleting..."))

            import shutil
            for Filename, Path, fullpath, IsFolder in self.get_tableview_selected():
                logger.info("Delete: " + fullpath)
                # if not os.path.exists(Path):    continue
                try:
                    if IsFolder:
                        os.removedirs(fullpath)
                    else:
                        os.remove(fullpath)
                except:
                    logger.error("Fail to delete file: %s" % fullpath)
            self.statusBar.showMessage(translate('statusbar',"Done."), 3000) 
Example 8
Project: pythoner   Author: jsRuner   File: wower_captcha.py    (license) View Source Project 6 votes vote down vote up
def __init__(self,filepath):
        self.imgpath = filepath
        self.fonts =[] #???????????
        self.str = '' #??????????

        binaryimg = 'wower_binary.png'

        cutdir = './cutimgs/'

        #????binary???cutimgs???
        if os.path.exists(binaryimg):
            os.remove(binaryimg)
        if os.path.exists(cutdir) and  os.path.isdir(cutdir):
            for f in os.listdir(cutdir):
                os.remove(cutdir+f)
            # os.removedirs(cutdir)
        #?????
        else:
            os.mkdir(cutdir)



    #??????????? 
Example 9
Project: pythoner   Author: jsRuner   File: captcha2.py    (license) View Source Project 6 votes vote down vote up
def __init__(self,filepath):
        self.imgpath = filepath
        self.fonts =[] #???????????
        self.str = '' #??????????

        binaryimg = 'binary.png'

        cutdir = './cutimgs/'

        #????binary???cutimgs???
        if os.path.exists(binaryimg):
            os.remove(binaryimg)
        if os.path.exists(cutdir) and  os.path.isdir(cutdir):
            for f in os.listdir(cutdir):
                os.remove(cutdir+f)
            os.removedirs(cutdir)
        #??????
        os.mkdir(cutdir)


    #??????????? 
Example 10
Project: pythoner   Author: jsRuner   File: hefei_captcha.py    (license) View Source Project 6 votes vote down vote up
def __init__(self,filepath):
        self.imgpath = filepath
        self.fonts =[] #???????????
        self.str = '' #??????????

        binaryimg = 'hefeicc_binary.png'

        cutdir = './cutimgs/'

        #????binary???cutimgs???
        if os.path.exists(binaryimg):
            os.remove(binaryimg)
        if os.path.exists(cutdir) and  os.path.isdir(cutdir):
            for f in os.listdir(cutdir):
                os.remove(cutdir+f)
            # os.removedirs(cutdir)
        #?????
        else:
            os.mkdir(cutdir)



    #??????????? 
Example 11
Project: pythoner   Author: jsRuner   File: captcha.py    (license) View Source Project 6 votes vote down vote up
def __init__(self,filepath):
        self.imgpath = filepath
        self.fonts =[] #???????????
        self.str = '' #??????????

        binaryimg = 'binary.png'

        cutdir = './cutimgs/'

        #????binary???cutimgs???
        if os.path.exists(binaryimg):
            os.remove(binaryimg)
        if os.path.exists(cutdir) and  os.path.isdir(cutdir):
            for f in os.listdir(cutdir):
                os.remove(cutdir+f)
            os.removedirs(cutdir)
        #??????
        os.mkdir(cutdir)


    #??????????? 
Example 12
Project: kalliope   Author: kalliope-project   File: test_file_manager.py    (license) View Source Project 6 votes vote down vote up
def test_create_directory(self):
        """
        Test to create a new directory.
        """
        # set up
        cache_path = "/tmp/kalliope/tests/testDirectory"
        if os.path.exists(cache_path):
            os.removedirs(cache_path)

        # Test FileManager.create_directory
        FileManager.create_directory(cache_path)
        self.assertTrue(os.path.exists(cache_path),
                        "Fail creating a directory to the path ")

        # Remove the directory
        os.removedirs(cache_path) 
Example 13
Project: earmark   Author: lowerquality   File: serve.py    (license) View Source Project 6 votes vote down vote up
def _process_upload(self, upl, session_id):
        path = os.path.join(self.db.dbdir, '_attachments', upl['path'])

        print 'processing', path

        # XXX: use a tempdir
        outdir = os.path.join(self.db.dbdir, upl['filename'])
        sess = SocketTranscriptionSession(outdir, self.factory, session_id, self.factory.gen_hclg_filename)

        BUF_LEN = 200
        for chunk in numm3.sound_chunks(path, nchannels=1, R=8000, chunksize=BUF_LEN):
            sess.feed(chunk)

        sess.stop()
        sess.join()

        # Clean up: remove the tempdir and the original upload
        os.removedirs(outdir)
        os.remove(path) 
Example 14
Project: python_mini_projeler   Author: o11   File: 1.py    (license) View Source Project 6 votes vote down vote up
def klasor_silme():
    dizin = {}
    print "\nno\t\tdosya ad?\n--\t\t---------"

    for a, i in enumerate(os.listdir(os.curdir)):
        print "{}\t\t{}".format(a, i)
        dizin[a] = i

    try:
        d_no = input("Silmek istedi?iniz dosya numaras?: ")
        path = dizin[d_no]
        os.removedirs(path)

    except KeyError:
        print "Klasör silinemedi !"
    except NameError:
        print "Klasör silinemedi !"
    except SyntaxError:
        print "Klasör silinemedi !" 
Example 15
Project: buildroot   Author: flutter   File: remove_stale_pyc_files.py    (license) View Source Project 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 '.svn' in dirname or '.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
Project: spyking-circus-ort   Author: spyking-circus   File: oscilloscope.py    (license) View Source Project 6 votes vote down vote up
def _initialize(self):

        self.data_available = False
        self.batch = None
        self.thresholds = None
        self.peaks = None
        self.data_lines = None
        self.threshold_lines = None
        self.peak_points = None
        self.output_directory = self.path
        if self.output_directory is not None:
            if os.path.exists(self.output_directory):
                # TODO check that the directory contains only .svg files.
                # os.removedirs(self.output_directory)
                pass
            os.makedirs(self.output_directory)

        return 
Example 17
Project: python-   Author: secondtonone1   File: __init__.py    (license) View Source Project 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 18
Project: spyking-circus   Author: spyking-circus   File: plot.py    (license) View Source Project 5 votes vote down vote up
def view_trigger_snippets(trigger_snippets, chans, save=None):
    # Create output directory if necessary.
    if os.path.exists(save):
        for f in os.listdir(save):
            p = os.path.join(save, f)
            os.remove(p)
        os.removedirs(save)
    os.makedirs(save)
    # Plot figures.
    fig = pylab.figure()
    for (c, chan) in enumerate(chans):
        ax = fig.add_subplot(1, 1, 1)
        for n in xrange(0, trigger_snippets.shape[2]):
            y = trigger_snippets[:, c, n]
            x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1)
            b = 0.5 + 0.5 * numpy.random.rand()
            ax.plot(x, y, color=(0.0, 0.0, b), linestyle='solid')
        y = numpy.mean(trigger_snippets[:, c, :], axis=1)
        x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1)
        ax.plot(x, y, color=(1.0, 0.0, 0.0), linestyle='solid')
        ax.grid(True)
        ax.set_xlim([numpy.amin(x), numpy.amax(x)])
        ax.set_title("Channel %d" %chan)
        ax.set_xlabel("time")
        ax.set_ylabel("amplitude")
        if save is not None:
            # Save plot.
            filename = "channel-%d.png" %chan
            path = os.path.join(save, filename)
            pylab.savefig(path)
        fig.clf()
    if save is None:
        pylab.show()
    else:
        pylab.close(fig)
    return 
Example 19
Project: my-first-blog   Author: AnkurBegining   File: __init__.py    (license) View Source Project 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 20
Project: Flask_Blog   Author: sugarguo   File: util.py    (GNU General Public License v3.0) View Source Project 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 21
Project: pip-update-requirements   Author: alanhamlett   File: misc.py    (BSD 2-Clause "Simplified" License) View Source Project 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
Project: chakin   Author: chakki-works   File: test_downloader.py    (MIT License) View Source Project 5 votes vote down vote up
def test_download_nest_dir(self):
        dir_name = 'data/ja'
        path = download(number=self.number, save_dir=dir_name)
        self.assertTrue(os.path.exists(path))
        os.remove(path)
        os.removedirs(dir_name) 
Example 23
Project: swjtu-pyscraper   Author: Desgard   File: __init__.py    (MIT License) View Source Project 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 24
Project: pytablereader   Author: thombashi   File: _url.py    (MIT License) View Source Project 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 25
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: __init__.py    (MIT License) View Source Project 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 26
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: __init__.py    (MIT License) View Source Project 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 27
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: __init__.py    (MIT License) View Source Project 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 28
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: __init__.py    (MIT License) View Source Project 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 29
Project: jira_worklog_scanner   Author: pgarneau   File: __init__.py    (license) View Source Project 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 30
Project: zanph   Author: zanph   File: __init__.py    (license) View Source Project 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 31
Project: hostapd-mana   Author: adde88   File: __init__.py    (license) View Source Project 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 32
Project: hostapd-mana   Author: adde88   File: util.py    (license) View Source Project 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 33
Project: zimfarm   Author: openzim   File: MWOffliner.py    (license) View Source Project 5 votes vote down vote up
def upload_file(self):
        self.current_index = 3
        self.step_started()

        start_time = datetime.utcnow()

        if not self.worker_finished_output_path.exists():
            os.makedirs(str(self.worker_finished_output_path))

        output = self.worker_running_output_path.joinpath(self.request.id)
        for source in output.iterdir():
            if not source.is_dir():
                destination = self.worker_finished_output_path.joinpath(source.parts[-1])
                os.rename(str(source), str(destination))
        os.removedirs(str(output))

        # remote_shell = 'ssh -p {port} -i {private_key} -oStrictHostKeyChecking=no' \
        #     .format(port=os.getenv('RSYNC_PORT', 22), private_key='/usr/src/id_rsa')
        # subprocess.run('rsync -azh -e="{remote_shell}" /mnt/ZimOutput/{id}/ [email protected]{remote_host}:/zimfiles'
        #                .format(remote_shell=remote_shell, id=self.request.id, remote_host=os.getenv('RSYNC_HOST')),
        #                shell=True)

        elapsed_seconds = (datetime.utcnow() - start_time).seconds
        self.step_finished(True, {
            'elapsed_seconds': elapsed_seconds
        }) 
Example 34
Project: linchpin   Author: CentOS-PaaS-SIG   File: test_linchpin_module_schema_check.py    (license) View Source Project 5 votes vote down vote up
def test_module_dir_params(self):
        """
        tests module with dir params
        """
        dir_name = tempfile.mkdtemp()
        invalid_params = {"data": dir_name, "schema": dir_name}
        self.options["module_args"] = json.dumps(invalid_params)
        results = run_module(self.options)
        msg = "Recursive directory not supported"
        output = results['failed'] and msg in results["msg"]
        os.removedirs(dir_name)
        assert_equal(output, True) 
Example 35
Project: linchpin   Author: CentOS-PaaS-SIG   File: test_linchpin_module_output_parser.py    (license) View Source Project 5 votes vote down vote up
def test_module_dir_params(self):
        """
        tests module with dir params
        """
        dir_name = tempfile.mkdtemp()
        invalid_params = {"output_file": dir_name}
        self.options["module_args"] = json.dumps(invalid_params)
        results = run_module(self.options)
        msg = "Recursive directory not supported"
        output = results['failed'] and msg in results["msg"]
        os.removedirs(dir_name)
        assert_equal(output, True) 
Example 36
Project: linchpin   Author: CentOS-PaaS-SIG   File: test_linchpin_module_os_hot_stack.py    (license) View Source Project 5 votes vote down vote up
def test_module_dir_params(self):
        """
        tests module with dir params
        """
        dir_name = tempfile.mkdtemp()
        invalid_params = {"stack_name": "testname",
                          "state": "present",
                          "template": dir_name}
        self.options["module_args"] = json.dumps(invalid_params)
        results = run_module(self.options)
        msg = "Recursive directory not supported"
        output = results['failed'] and msg in results["msg"]
        assert_equal(output, True)
        os.removedirs(dir_name) 
Example 37
Project: Sci-Finder   Author: snverse   File: __init__.py    (license) View Source Project 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 38
Project: Sci-Finder   Author: snverse   File: __init__.py    (license) View Source Project 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 39
Project: vsphere-storage-for-docker   Author: vmware   File: vmdk_ops_test.py    (license) View Source Project 5 votes vote down vote up
def clean_path(path):
        if not path:
            logging.info("Directory clean up - empty dir passed")
            return

        logging.info("Directory clean up - removing  %s", path)
        try:
            # TODO: need to use osfs-rmdir on VSAN. For now jus yell if it failed
            os.removedirs(path)
        except Exception as e:
            logging.warning("Directory clean up failed  -  %s, err: %s", path, e) 
Example 40
Project: ascii-art-py   Author: blinglnav   File: __init__.py    (license) View Source Project 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 41
Project: avocado-misc-tests   Author: avocado-framework   File: lvsetup.py    (license) View Source Project 5 votes vote down vote up
def tearDown(self):
        """
        Clear all PV,VG, LV and snapshots created by the test.
        """
        # Remove created VG and unmount from base directory
        errs = []
        for ramdisk in self.ramdisks:
            try:
                lv_utils.vg_ramdisk_cleanup(*ramdisk)
            except Exception as exc:
                errs.append("Fail to cleanup ramdisk %s: %s" % (ramdisk, exc))
        if errs:
            self.error("\n".join(errs))
        os.removedirs(self.mount_loc) 
Example 42
Project: ivaochdoc   Author: ivaoch   File: __init__.py    (license) View Source Project 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 43
Project: aws-cfn-plex   Author: lordmuffin   File: __init__.py    (license) View Source Project 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 44
Project: django   Author: alexsukhrin   File: __init__.py    (license) View Source Project 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 45
Project: RPoint   Author: george17-meet   File: __init__.py    (license) View Source Project 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 46
Project: Automation-Scripts   Author: MohammedRashad   File: Alpha_Organizer.py    (license) View Source Project 5 votes vote down vote up
def clean():
    absolute_path = os.path.abspath(__file__)
    mypath = os.path.dirname(absolute_path)

    for root, dirs, files in os.walk(mypath,topdown=False):
        for name in dirs:
            fname = join(root,name)
            if not os.listdir(fname): #to check wither the dir is empty
                 os.removedirs(fname) 
Example 47
Project: isni-reconcile   Author: cmh2166   File: __init__.py    (license) View Source Project 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 48
Project: Comictagger   Author: dickloraine   File: test_UnRAR2.py    (license) View Source Project 5 votes vote down vote up
def cleanup(dir='test'):
    for path, dirs, files in os.walk(dir):
        for fn in files:
            os.remove(os.path.join(path, fn))
        for dir in dirs:
            os.removedirs(os.path.join(path, dir))


# basic test 
Example 49
Project: AshsSDK   Author: thehappydinoa   File: __init__.py    (license) View Source Project 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 50
Project: habilitacion   Author: GabrielBD   File: __init__.py    (license) View Source Project 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