Search code examples
pythonwindowslistdir

Ignore "System Volume Information" in Python listdir


I'm currently trying to get all files on a Windows volume in order to copy certain files. Copying from, let's say a folder to another folder works just fine, but when trying to listdir and then loop over the found files of the volume, I'm just greeted by an access denied exception for "System Volume Information".

How can I ignore/skip this in the loop?

I'm using a recursive function, calling it the first time with the root path of the volume itself.

def list_all(path):
files = os.listdir(path)

for file in files:
    low_path = os.path.join(path, file)

    if os.path.isdir(low_path):
        list_all(low_path)
    else:
        # shutil.copy()

Solution

  • You can add a try/except block

    def list_all(path):
    files = os.listdir(path)
    
    try:
      files.remove("System Volume Information")
    except:
      print("System Volume Information not present in this directory")
    
    
    for file in files:
        low_path = os.path.join(path, file)
    
        if os.path.isdir(low_path):
            list_all(low_path)
        else:
            # shutil.copy()