Python - How to list all the files

Sometimes, we need to list all the files in a folder or sub folder in Python.

In this post, I will show you how to use the glob function to achieve this.

Solution

First, let’s take a look at the file structure of the example.

1
2
3
4
5
6
7
8
9
10
./data
├── level-0-0
│   └── file-0.txt
├── level-0-1
│   ├── file-1.txt
│   └── file-2.txt
├── level-0-2
├── file-3.txt
├── file-4.txt
├── file-5.txt

List all the files in single current folder

Now, we can do this by the following code.

1
2
3
4
import glob
files = glob.glob('./data/*.txt')
for file in files:
print(file)

Here is the output.

1
2
3
./data/file-5.txt
./data/file-4.txt
./data/file-3.txt

List all the files in folder recursively

However, we also can list all the files recursively.

1
2
3
4
import glob
files = glob.glob('./data/**/*.txt', recursive=True)
for file in files:
print(file)

Now, we can see all the files in data folder.

1
2
3
4
5
6
./data/file-5.txt
./data/file-4.txt
./data/file-3.txt
./data/level-0-1/file-2.txt
./data/level-0-1/file-1.txt
./data/level-0-0/file-0.txt

Tips

Also, we can use regex with glob

1
2
3
4
import glob
files = glob.glob('./data/**/*[2-3].txt', recursive=True)
for file in files:
print(file)
1
2
./data/file-3.txt
./data/level-0-1/file-2.txt

🙂

相關文章