Python: os.path.isdir /isfile /exists not working, returning False when they should return True
Question: So, here is my little program. It should print all files in a given directory
+ all files in every subdirectory.

    
    
    import os
    
    def listFiles(directory):
        dirList = os.listdir(directory)
        printList = []
        for i in dirList:
            i = os.path.join(directory,i)
          #  print(i)
            if os.path.isdir(i):
                printList[len(dirList):] = listFiles(i)
            else:
                printList.append(i)
        return printList
    
    directory = 'C:\Python32\Lib'
    listFiles(directory)
    a = listFiles(directory)
    
    for i in a:
        print(i)
    

What's the problem: os.path.isdir(i) isn't working properly - for example, if
I try

    
    
    os.path.isfile('C:\Python32\Lib\concurrent\futures\process.py')
    os.path.exists('C:\Python32\Lib\concurrent\futures\process.py')
    os.path.isdir('C:\Python32\Lib\concurrent\futures')
    

I always get False instead of True (it works ok for some of the
subdirectories). If I uncomment print(i) it prints everything just fine but it
also prints directories - I want just to print files. What should I do?


Answer: Your `printList[len(dirList):] = listFiles(i)` is going to overwrite values
every loop.

If all your entries in `dirList` are directories, for example, you'll end up
with removing entries from `printList` as you loop over each subdir:

    
    
    >>> printList = []
    >>> len_dirlist = 2  # make up a size
    >>> printList[len_dirlist:] = ['foo', 'bar', 'baz'] # subdir 1 read
    >>> printList
    ['foo', 'bar', 'baz']
    >>> printList[len_dirlist:] = ['spam', 'ham', 'eggs'] # subdir 2 read
    >>> printList
    ['foo', 'bar', 'spam', 'ham', 'eggs']  # Wait, where did 'baz' go?
    

You want to use `.extend()` instead when adding items to the end of your list.

Note that on Windows, you don't have to use backslashes as path separators,
it's better to use forward slashes, as these do not have special meaning in
Python strings:

    
    
    'C:/Python32/Lib/concurrent/futures/process.py'
    

Alternatively, use `r''` _raw_ string literals to remove the chance
backslashes are interpreted as character escapes:

    
    
    r'C:\Python32\Lib\concurrent\futures\process.py'
    

