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

前端 未结 10 1928
暖寄归人
暖寄归人 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:36

    You can use this simple code:

    dir_contents = [x for x in os.listdir('.') if not x.startswith('.')]
    if len(dir_contents) > 0:
        print("Directory contains files")
    

    It checks for files and directories in the current working directory (.). You can change . in os.listdir() to check any other directory.

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

    With pathlib this can be done as follows:

    import pathlib
    
    # helper function
    def is_empty(_dir: pathlib.PAth) -> bool:
        return not bool([_ for _ in _dir.iterdir()])
    
    # create empty dir
    _dir = pathlib.Path("abc")
    
    # check if dir empty
    is_empty(_dir)  # will retuen True
    
    # add file s to folder and call it again
    
    
    
    0 讨论(0)
  • 2020-12-01 12:38

    I have follews Bash checking if folder has contents answer.

    os.walk('.') returns the complete files under a directory and if there thousands it may be inefficient. Instead following command find "$target" -mindepth 1 -print -quit returns first found file and quits. If it returns an empty string, which means folder is empty.

    You can check if a directory is empty using find, and processing its output

    def is_dir_empty(absolute_path):
        cmd = ["find", absolute_path, "-mindepth", "1", "-print", "-quit"]
        output = subprocess.check_output(cmd).decode("utf-8").strip()
        return not output
    
    print is_dir_empty("some/path/here")
    
    0 讨论(0)
  • 2020-12-01 12:41

    Adding to @Jon Clements’ pathlib answer, I wanted to check if the folder is empty with pathlib but without creating a set:

    from pathlib import Path
    
    # shorter version from @vogdb
    is_empty = not any(Path('some/path/here').iterdir())
    
    # similar but unnecessary complex
    is_empty = not bool(sorted(Path('some/path/here').rglob('*')))
    

    vogdb method attempts iterates over all files in the given directory. If there is no files, any() will be False. We negate it with not so that is_empty is True if no files and False if files.

    sorted(Path(path_here).rglob('*')) return a list of sorted PosixPah items. If there is no items, it returns an empty list, which is False. So is_empty will be True if the path is empty and false if the path have something

    Similar idea results {} and [] gives the same: enter image description here

    0 讨论(0)
提交回复
热议问题