Get A List Of Files From A Directory With Python

August - 2018

This works to get a list of files recursively:

import glob
from os.path import isfile

source_directory = 'some/path/to/files'

source_files = [
    file for file in glob.glob(
        f"{source_directory}/**/*",
        recursive=True
    )
    if isfile(file)
]

NOTE: Does not pick up . invisible files.


Old Notes


Getting a list of files in python

Glob works:

import glob
    
schedule_files = glob.glob(*.xml)
    
for schedule_file in schedule_files:
    print(schedule_file)

You can also do recursive like this:

file_list = glob.glob(f'{root_path}/**/*.mp3', recursive=True)

TODO: Test with different structures to confirm and provide examples.


#!/usr/bin/env python
    
from os import listdir
from os.path import isfile, join
    
source_dir = 'some-dir'
file_list = [f for f in listdir(source_dir) if isfile(join(source_dir, f))]

This returns the list of filenames including the extension but without the directory path.

This does include files that start with a .


Directories ignoring hidden files:

```python
#!/usr/bin/env python3

from os import listdir

source_dir = 'designs'
dir_list = [d for d in listdir(source_dir) if d[0] != '.']
print(dir_list)
```


    
---

via: https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory