How to get all of the immediate subdirectories in Python

前端 未结 15 1632
旧时难觅i
旧时难觅i 2020-11-29 17:09

I\'m trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions).

I\'m getting bogged down

相关标签:
15条回答
  • 2020-11-29 17:33

    Why has no one mentioned glob? glob lets you use Unix-style pathname expansion, and is my go to function for almost everything that needs to find more than one path name. It makes it very easy:

    from glob import glob
    paths = glob('*/')
    

    Note that glob will return the directory with the final slash (as unix would) while most path based solutions will omit the final slash.

    0 讨论(0)
  • 2020-11-29 17:33

    os.walk is your friend in this situation.

    Straight from the documentation:

    walk() generates the file names in a directory tree, by walking the tree either top down or bottom up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

    0 讨论(0)
  • 2020-11-29 17:37
    import glob
    import os
    
    def child_dirs(path):
         cd = os.getcwd()        # save the current working directory
         os.chdir(path)          # change directory 
         dirs = glob.glob("*/")  # get all the subdirectories
         os.chdir(cd)            # change directory to the script original location
         return dirs
    

    The child_dirs function takes a path a directory and returns a list of the immediate subdirectories in it.

    dir
     |
      -- dir_1
      -- dir_2
    
    child_dirs('dir') -> ['dir_1', 'dir_2']
    
    0 讨论(0)
  • 2020-11-29 17:39

    Here's one way:

    import os
    import shutil
    
    def copy_over(path, from_name, to_name):
      for path, dirname, fnames in os.walk(path):
        for fname in fnames:
          if fname == from_name:
            shutil.copy(os.path.join(path, from_name), os.path.join(path, to_name))
    
    
    copy_over('.', 'index.tpl', 'index.html')
    
    0 讨论(0)
  • 2020-11-29 17:40

    I have to mention the path.py library, which I use very often.

    Fetching the immediate subdirectories become as simple as that:

    my_dir.dirs()

    The full working example is:

    from path import Path
    
    my_directory = Path("path/to/my/directory")
    
    subdirs = my_directory.dirs()
    

    NB: my_directory still can be manipulated as a string, since Path is a subclass of string, but providing a bunch of useful methods for manipulating paths

    0 讨论(0)
  • 2020-11-29 17:45
    import pathlib
    
    
    def list_dir(dir):
        path = pathlib.Path(dir)
        dir = []
        try:
            for item in path.iterdir():
                if item.is_dir():
                    dir.append(item)
            return dir
        except FileNotFoundError:
            print('Invalid directory')
    
    0 讨论(0)
提交回复
热议问题