pytutorial/glob
David Rotermund 2bea74ff9b
Update README.md
Signed-off-by: David Rotermund <54365609+davrot@users.noreply.github.com>
2023-12-02 02:13:20 +01:00
..
README.md Update README.md 2023-12-02 02:13:20 +01:00

glob -- Finding files in a directory

Goal

We want to deal with many files in a directory. What is an easy way to get the filename in a directory?

Questions to David Rotermund

Creating test files

from pathlib import Path

Path("Testfile_1.mat").touch()
Path("Testfile_2.mat").touch()
Path("Testfile_10.mat").touch()
Path("Testfile_3.mat").touch()

Using glob in a for-loop

import glob

for filename in glob.glob("*.mat"):
    print(filename)
Testfile_1.mat
Testfile_2.mat
Testfile_10.mat
Testfile_3.mat

Using glob to create a list

import glob

list = glob.glob("*.mat")
print(list)
['Testfile_1.mat', 'Testfile_2.mat', 'Testfile_10.mat', 'Testfile_3.mat']

Sorting the filenames

import glob

list = sorted(glob.glob("*.mat"))
print(list)
['Testfile_1.mat', 'Testfile_10.mat', 'Testfile_2.mat', 'Testfile_3.mat']