Python os.path.rstrip() Examples

The following are 13 code examples of os.path.rstrip(). 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.path , or try the search function .
Example #1
Source File: webserver.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, data):
        super().__init__(data)
        try:
            parsed = json.loads(data)
        except ValueError:
            raise testprocess.InvalidLine(data)

        assert isinstance(parsed, dict)
        assert set(parsed.keys()) == {'path', 'verb', 'status'}

        self.verb = parsed['verb']

        path = parsed['path']
        self.path = '/' if path == '/' else path.rstrip('/')

        self.status = parsed['status']
        self._check_status() 
Example #2
Source File: prompt.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def _insert_path(self, index, *, clicked=True):
        """Handle an element selection.

        Args:
            index: The QModelIndex of the selected element.
            clicked: Whether the element was clicked.
        """
        if index == QModelIndex():
            path = os.path.join(self._file_model.rootPath(), self._to_complete)
        else:
            path = os.path.normpath(self._file_model.filePath(index))

        if clicked:
            path += os.sep
        else:
            # On Windows, when we have C:\foo and tab over .., we get C:\
            path = path.rstrip(os.sep)

        log.prompt.debug('Inserting path {}'.format(path))
        self._lineedit.setText(path)
        self._lineedit.setFocus()
        self._set_fileview_root(path, tabbed=True)
        if clicked:
            # Avoid having a ..-subtree highlighted
            self._file_view.setCurrentIndex(QModelIndex()) 
Example #3
Source File: sim_files.py    From simLAB with GNU General Public License v2.0 6 votes vote down vote up
def findFileOrDirectory(self, path):
        path = self.getFilePath(path)
        if not path:
            return None, None
        xmlPath = self.simXml.getXmlPath(path)
        node = self.simXml.find(xmlPath)
        if node == None:
            if path[-1] != "/":
                #try to select direcotry
                path += "/"
                xmlPath = self.simXml.getXmlPath(path)
                node = self.simXml.find(xmlPath)
            else:
                #try to select file
                path = path.rstrip("/")
                xmlPath = self.simXml.getXmlPath(path)
                node = self.simXml.find(xmlPath)
            if node == None:
                logging.error("Failed to select: %s" %xmlPath)
                return None, None
        return node, xmlPath 
Example #4
Source File: sftp.py    From statik with MIT License 6 votes vote down vote up
def sftp_mkdir_p(sftp, remote_directory):
    """Ensures that the given path exists on the target server.
    Adapted from: https://stackoverflow.com/a/14819803"""
    if remote_directory == '/':
        # absolute path so change directory to root
        sftp.chdir('/')
        return
    if remote_directory == '':
        # top-level relative directory must exist
        return
    try:
        sftp.chdir(remote_directory) # sub-directory exists
    except IOError:
        path_parts = remote_directory.rstrip("/").split("/")
        dirname = "/".join(path_parts[:-1])
        basename = path_parts[-1]
        sftp_mkdir_p(sftp, dirname) # make parent directories
        logger.debug("Creating remote folder: %s" % remote_directory)
        sftp.mkdir(basename) # sub-directory missing, so created it
        sftp.chdir(basename) 
Example #5
Source File: client.py    From python-egnyte with MIT License 6 votes vote down vote up
def bulk_download(self, paths, local_dir, overwrite=False, progress_callbacks=None):
        """
        Transfer many files or directories to Cloud File System.

        * paths - list of local file paths
        * target - Path in CFS to upload to
        * progress_callbacks - Callback object (see ProgressCallbacks)
        """
        if progress_callbacks is None:
            progress_callbacks = ProgressCallbacks()
        for path in paths:
            progress_callbacks.getting_info(path)
            obj = self.get(path)
            progress_callbacks.got_info(obj)
            root_path = path[:path.rstrip('/').rfind('/')]  # take all segments expect last one
            if obj.is_folder:
                items = obj.files + obj.folders
            else:
                items = (obj,)
            self._bulk_download(items, root_path, local_dir, overwrite, progress_callbacks)
        progress_callbacks.finished() 
Example #6
Source File: io.py    From vergeml with MIT License 5 votes vote down vote up
def scan(self, path, exclude=[]) -> List[str]:
        """Scan path for matching files.

        :param path: the path to scan
        :param exclude: a list of directories to exclude

        :return: a list of sorted filenames
        """
        res = []
        path = path.rstrip("/").rstrip("\\")
        for pat in self.input_patterns:
            res.extend(glob.glob(path + os.sep + pat, recursive=True))

        res = list(filter(lambda p: os.path.isfile(p), res))

        if exclude:
            def excluded(path):
                for e in exclude:
                    if path.startswith(e):
                        return True
                return False

            res = list(filter(lambda p: not excluded(p), res))

        return sorted(res) 
Example #7
Source File: prompt.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def _set_fileview_root(self, path, *, tabbed=False):
        """Set the root path for the file display."""
        separators = os.sep
        if os.altsep is not None:
            separators += os.altsep

        dirname = os.path.dirname(path)
        basename = os.path.basename(path)
        if not tabbed:
            self._to_complete = ''

        try:
            if not path:
                pass
            elif path in separators and os.path.isdir(path):
                # Input "/" -> don't strip anything
                pass
            elif path[-1] in separators and os.path.isdir(path):
                # Input like /foo/bar/ -> show /foo/bar/ contents
                path = path.rstrip(separators)
            elif os.path.isdir(dirname) and not tabbed:
                # Input like /foo/ba -> show /foo contents
                path = dirname
                self._to_complete = basename
            else:
                return
        except OSError:
            log.prompt.exception("Failed to get directory information")
            return

        root = self._file_model.setRootPath(path)
        self._file_view.setRootIndex(root) 
Example #8
Source File: kvm_local_deploy_v2.py    From bubble-toolkit with Apache License 2.0 5 votes vote down vote up
def format_path(self, path):
        return "%s%s" % (path.rstrip("/"), "/")

    # Test if file exists 
Example #9
Source File: kvm_local_deploy.py    From bubble-toolkit with Apache License 2.0 5 votes vote down vote up
def format_path(self, path):
        return "%s%s" % (path.rstrip("/"), "/")

    # Test if file exists 
Example #10
Source File: utils.py    From statik with MIT License 5 votes vote down vote up
def add_url_path_component(path, component):
    return '%s/%s' % (path.rstrip('/'), component.lstrip('/')) 
Example #11
Source File: sftp.py    From statik with MIT License 5 votes vote down vote up
def rm_path_via_sftp(sftp, path):
    """Removes the given path using the specified SFTP connection."""
    logger.debug("Removing remote folder and all contents: %s" % path)
    files = sftp.listdir(path)
    for f in files:
        filepath = path.rstrip("/\\") + "/" + f.strip("/\\")
        try:
            sftp.remove(filepath)
        except IOError:
            # it's probably a directory
            rm_path_via_sftp(sftp, filepath) 
Example #12
Source File: client.py    From python-egnyte with MIT License 5 votes vote down vote up
def folder(self, path="/Shared", **kwargs):
        """Get a Folder object for the specified path"""
        return resources.Folder(self, path=path.rstrip('/'), **kwargs) 
Example #13
Source File: client.py    From python-egnyte with MIT License 5 votes vote down vote up
def _bulk_download(self, items, root_path, local_dir, overwrite, progress_callbacks):
        root_len = len(root_path.rstrip('/')) + 1
        queue = collections.deque(items)
        while True:
            try:
                obj = queue.popleft()
            except IndexError:
                break
            relpath = obj.path[root_len:].strip('/')
            local_path = os.path.join(local_dir, relpath.replace('/', os.sep))
            dir_path = os.path.dirname(local_path)
            if not os.path.isdir(dir_path):
                if os.path.exists(dir_path):
                    if overwrite:
                        os.unlink(local_path)
                    else:
                        progress_callbacks.skipped(obj, "Existing file conflicts with cloud folder")
                        continue
                os.makedirs(dir_path)
            if obj.is_folder:
                # schedule contents for later, files first
                if obj.files is None:
                    progress_callbacks.getting_info(obj.path)
                    obj.list()
                    progress_callbacks.got_info(obj)
                queue.extend(obj.files)
                queue.extend(obj.folders)
            else:
                if os.path.exists(local_path):
                    if overwrite:
                        if os.path.isdir(local_path) and not os.path.islink(local_path):
                            shutil.rmtree(local_path)
                        else:
                            os.unlink(local_path)
                    else:
                        progress_callbacks.skipped(obj, "Existing file conflicts with cloud file")
                        continue
                progress_callbacks.download_start(local_path, obj, obj.size)
                obj.download().save_to(local_path, progress_callbacks.download_progress)
                progress_callbacks.download_finish(obj)