How to check to see if a folder contains files using python 3

前端 未结 10 1897
暖寄归人
暖寄归人 2020-12-01 11:40

I\'ve searched everywhere for this answer but can\'t find it.

I\'m trying to come up with a script that will search for a particular subfolder then check if it conta

相关标签:
10条回答
  • 2020-12-01 12:20

    Check if the folder contains files:

    import os
    import shutil
    
    if len(os.listdir(folder_path)) == 0: # Check is empty..
        shutil.rmtree(folder_path) # Delete..
    
    0 讨论(0)
  • 2020-12-01 12:22

    You can make use of the new pathlib library introduced in Python 3.4 to extract all non-empty subdirectories recursively, eg:

    import pathlib
    
    root = pathlib.Path('some/path/here')
    non_empty_dirs = {str(p.parent) for p in root.rglob('*') if p.is_file()}
    

    Since you have to walk the tree anyway, we build a set of the parent directories where a file is present which results in a set of directories that contain files - then do as you wish with the result.

    0 讨论(0)
  • 2020-12-01 12:25

    If you can delete the directory, you can use this:

    my_path = os.path.abspath("something")               
    try:
        os.rmdir(my_path)
        is_empty = True
        # Do you need to keep the directory? Recreate it!
        # os.makedirs(my_path, exist_ok=True)
    except OSError:
        is_empty = False
    
    if is_empty:
        pass
    

    The os.rmdir only removes a directory if it is empty, otherwise it throws the OSError exception.

    You can find a discussion about this on:

    1. https://bytes.com/topic/python/answers/157394-how-determine-if-folder-empty

    For example, deleting an empty directory is fine when you are planing to do a git clone, but not if you are checking beforehand whether the directory is empty, so your program does not throw an empty directory error.

    0 讨论(0)
  • 2020-12-01 12:31

    You can directly use the generator instead of converting to a set or (ordered) list first:

    from pathlib import Path
    
    p = Path('abc')
    
    def check_dir(p):
    
        if not p.exists():
            print('This directory is non-existent')
            return
    
        try:
            next(p.rglob('*'))
        except StopIteration:
            print('This directory is empty')
            return
    
        print('OK')
    

    0 讨论(0)
  • entities = os.listdir(dirpath)
    for entity in entities:
        if os.path.isfile(entity):
            print(dirpath)
            break
    
    0 讨论(0)
  • 2020-12-01 12:36

    'files' already tells you whats in the directory. Just check it:

    for dirpath, dirnames, files in os.walk('.'):
        if files:
            print(dirpath, 'has files')
        if not files:
            print(dirpath, 'is empty')
    
    0 讨论(0)
提交回复
热议问题