two questions - no common theme

suryaprakashg at gmail.com suryaprakashg at gmail.com
Wed Feb 9 15:25:35 EST 2005


 def walktree(self,top=".", depthfirst=False):
        """
        Walk a directory tree, starting from 'top'

        This code is based on os.path.walk, with the callback function
        replaced by a yield and recursion replaced by iteration
        """
        if type(top) != types.StringType:
            raise TypeError("top must be a string")

        # decide which end of the stack to pop
        if depthfirst:
            index = -1
        else:
            index = 0

        dirstack = [top]
        while dirstack:
            top = dirstack.pop(index)
            try:
                names = os.listdir(top)
            except os.error:
                 return
            yield top, names
            dirs = []
            for name in names:
                name = os.path.join(top, name)
                try:
                    st = os.lstat(name)
                except os.error:
                    continue
                if stat.S_ISDIR(st.st_mode):
                    dirs.append(name)
            # the depth-first results look 'backwards' to me
            # so I'm changing them to fit my expectations
            if depthfirst:
                dirs.reverse()
            dirstack.extend(dirs)


this function might be useful


Sean McIlroy wrote:
> And now for a pair of questions that are completely different:
>
> 1) I'd like to be able to bind callbacks to presses of the arrow
> buttons on the keyboard. How do you say that in Tkinter?
>
> 2) The function 'listdir' in os.path returns a list of all the files
> in the given directory - how do I get hold of a list of its
> subdirectories?
> 
> Any help will be greatly appreciated.
> 
> Peace,
> STM




More information about the Python-list mailing list