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

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

提交回复
热议问题