Python Working with Folders
What you will learn
- Listing a folder with
iterdir() - Finding files with
globandrglobpatterns - Walking a tree with
os.walk - Copying, moving and deleting with
shutil - Filtering by type, extension and size
- Temporary folders
1. A sample folder
The examples use this tree, which a short script creates (all of it is deleted again at the end of the lesson's code):
project/
├── readme.txt
├── notes.md
├── docs/
│ ├── guide.md
│ └── img/
│ └── logo.png
└── src/
├── main.py
├── util.py
└── data/
├── a.csv
└── b.csv
from pathlib import Path
root = Path("project")
files = {"readme.txt": "hi", "notes.md": "n", "src/main.py": "print(1)\n",
"src/util.py": "x=1\n", "src/data/a.csv": "1,2\n", "src/data/b.csv": "3,4\n",
"docs/guide.md": "# g\n", "docs/img/logo.png": "png"}
for rel, text in files.items():
p = root / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(text)
(Lesson 15.4 explained mkdir and write_text.)
2. Listing one folder: iterdir
iterdir() yields the items directly inside a folder (files and folders, in no guaranteed order, so sort when order matters):
print(sorted(x.name for x in root.iterdir()))
print([(x.name, x.is_dir()) for x in sorted(root.iterdir())])
['docs', 'notes.md', 'readme.txt', 'src']
[('docs', True), ('notes.md', False), ('readme.txt', False), ('src', True)]
It does not go into sub-folders. os.listdir(root) gives just the names as strings.
Quick check: does `iterdir()` list the files inside `src`?
No. Only the items directly in the folder; src appears as one item.
3. Finding files: glob and rglob
glob(pattern) finds items whose names match a pattern in a folder:
| Pattern part | Matches |
|---|---|
* |
any number of characters (not /) |
? |
exactly one character |
[abc] |
one of the listed characters |
** |
any depth of sub-folders (any folder, including none) |
print(sorted(p.name for p in root.glob("*.txt")))
print(sorted(p.name for p in root.glob("*.md")))
print(sorted(p.as_posix() for p in root.glob("*/*.md")))
print(sorted(p.name for p in root.glob("src/*.py")))
print(sorted(p.name for p in root.glob("src/[mu]*.py")))
print(sorted(p.name for p in root.glob("src/???.py")))
['readme.txt']
['notes.md']
['project/docs/guide.md']
['main.py', 'util.py']
['main.py', 'util.py']
[]
*.mdfinds onlynotes.mdin the top folder.*/*.mdlooks one level down:docs/guide.md.src/???.pyfinds nothing, becausemainandutilhave four letters, not three.
To search all levels, use rglob (recursive glob), or ** inside glob:
print(sorted(p.as_posix() for p in root.rglob("*.csv")))
print(sorted(p.as_posix() for p in root.glob("**/*.md")))
print(len(list(root.rglob("*"))), len([p for p in root.rglob("*") if p.is_file()]))
['project/src/data/a.csv', 'project/src/data/b.csv']
['project/docs/guide.md', 'project/notes.md']
12 8
rglob("*") yields everything below (12 items: 8 files and 4 folders). The results are produced lazily, so list(...) or sorted(...) collect them. Matching is case-sensitive on some systems (Linux) and not on others (Windows); the organiser example below lower-cases the suffix to avoid surprises.
4. Walking a tree: os.walk
os.walk(top) visits every folder and gives, for each, its path, a list of its sub-folder names and a list of its file names:
import os
for dirpath, dirnames, filenames in os.walk(root):
print(Path(dirpath).as_posix(), sorted(dirnames), sorted(filenames))
project ['docs', 'src'] ['notes.md', 'readme.txt']
project/docs ['img'] ['guide.md']
project/docs/img [] ['logo.png']
project/src ['data'] ['main.py', 'util.py']
project/src/data [] ['a.csv', 'b.csv']
Use os.walk when you need to treat folders and their files together (for example to skip some sub-folders by editing dirnames). For plain "find these files", rglob is simpler.
5. Filtering and summarising
Combine globbing with is_file(), suffix and stat() (file facts):
from collections import Counter
print(Counter(p.suffix for p in root.rglob("*") if p.is_file()))
found = [p for p in root.rglob("*") if p.is_file() and p.stat().st_size > 5]
print(sorted(p.name for p in found))
print(next(root.glob("*.zip"), None))
print(sorted(p.relative_to(root).as_posix() for p in root.rglob("*.py")))
Counter({'.md': 2, '.py': 2, '.csv': 2, '.txt': 1, '.png': 1})
['main.py']
None
['src/main.py', 'src/util.py']
Counter(lesson 17.3) counts files per extension.p.stat().st_sizeis the size in bytes; onlymain.pyhas more than 5 bytes here. (Exact sizes can differ between systems because of line-ending conversion, lesson 15.1.)next(iterator, None)returnsNonewhen nothing matches, which is a tidy "first match or nothing".relative_to(root)shortens a path to be relative to the folder.
6. Copy, move, delete: shutil
pathlib can rename and delete single items. The shutil module (shell utilities) handles copying and whole folders:
import shutil
shutil.copy(root / "readme.txt", root / "readme_copy.txt") # one file
shutil.copytree(root / "docs", root / "docs_copy") # a whole folder
print(sorted(p.name for p in (root / "docs_copy").rglob("*")))
shutil.move(str(root / "notes.md"), str(root / "docs" / "notes.md"))
print((root / "notes.md").exists(), (root / "docs" / "notes.md").exists())
['guide.md', 'img', 'logo.png']
False True
shutil.copy(src, dst)copies a file (copy2also keeps the time stamps).shutil.copytree(src, dst)copies a folder and its contents. The destination must not exist (FileExistsError), unless you passdirs_exist_ok=True.shutil.move(src, dst)moves a file or folder, even across drives.- (The calls above use
str(...)formoveout of habit; modern Python acceptsPathobjects too.)
Deleting:
try:
(root / "docs").rmdir()
except OSError as e:
print("OSError:", type(e).__name__)
shutil.rmtree(root / "docs_copy")
print((root / "docs_copy").exists())
OSError: OSError
False
rmdir()only removes empty folders, and otherwise raises anOSError(the exact message depends on the system).shutil.rmtree(folder)deletes a folder and everything in it, permanently. Double-check the path; never pass a folder built from unchecked user input.
7. Changing many files
A loop applies the same action to every match. For example, rename every .csv to .txt:
for p in root.rglob("*.csv"):
p.rename(p.with_suffix(".txt"))
print(sorted(p.name for p in root.rglob("*.txt")))
['a.txt', 'b.txt', 'readme.txt', 'readme_copy.txt']
When you change files while looping, collect the list first (list(root.rglob(...))) if the action could create new matches.
8. Temporary folders
For scratch work, tempfile.TemporaryDirectory() makes a folder that is deleted automatically at the end of the with block (lesson 14.6):
import tempfile
with tempfile.TemporaryDirectory() as tmp:
t = Path(tmp) / "x.txt"
t.write_text("temp")
print(t.read_text(), Path(tmp).is_dir())
print(Path(tmp).exists())
temp True
False
It is perfect for tests and for building files that are then processed and thrown away.
Worked example: tidying a downloads folder
Files in downloads are moved into sub-folders by type: images, documents, data, and other. Existing folders (like keep) are left alone. Upper-case extensions such as .JPG are handled.
from pathlib import Path
import shutil
FOLDERS = {".jpg": "images", ".png": "images", ".pdf": "documents",
".txt": "documents", ".csv": "data"}
def organise(folder):
folder = Path(folder)
moved = {}
for item in sorted(folder.iterdir()):
if not item.is_file():
continue
target_name = FOLDERS.get(item.suffix.lower(), "other")
target = folder / target_name
target.mkdir(exist_ok=True)
shutil.move(str(item), str(target / item.name))
moved.setdefault(target_name, []).append(item.name)
return moved
downloads = Path("downloads")
downloads.mkdir(exist_ok=True)
for name in ["cv.pdf", "photo.JPG", "sales.csv", "notes.txt", "setup.exe", "logo.png"]:
(downloads / name).write_text("x")
(downloads / "keep").mkdir(exist_ok=True)
result = organise(downloads)
for folder, names in sorted(result.items()):
print(f"{folder}: {names}")
print(sorted(p.relative_to(downloads).as_posix() for p in downloads.rglob("*") if p.is_file()))
print(sorted(p.name for p in downloads.iterdir()))
shutil.rmtree(downloads)
data: ['sales.csv']
documents: ['cv.pdf', 'notes.txt']
images: ['logo.png', 'photo.JPG']
other: ['setup.exe']
['data/sales.csv', 'documents/cv.pdf', 'documents/notes.txt', 'images/logo.png', 'images/photo.JPG', 'other/setup.exe']
['data', 'documents', 'images', 'keep', 'other']
| Step | Idea |
|---|---|
sorted(folder.iterdir()) |
a fixed order, and the list is made before the folders are created |
if not item.is_file(): continue |
leaves the folder keep alone |
FOLDERS.get(item.suffix.lower(), "other") |
a lookup table with a default |
mkdir(exist_ok=True) |
creates the target folder when first needed |
moved.setdefault(name, []).append(...) |
groups names per folder (lesson 9.3) |
The file names are made up, and every file here is a one-letter test file. Before running such a script on a real folder, test it on a copy.
Common mistakes
- Expecting
iterdir()orglob("*")to include sub-folder contents (userglob). - Relying on the order of results (sort them).
- Deleting with
rmtreeon the wrong path. - Moving files while looping over a live
iterdir()that you are changing (collect the list first). - Overwriting files by moving into a folder that already has the same file name.
- Forgetting case differences (
.JPGversus.jpg). - Running a bulk-change script on real data without testing on a copy.
Key takeaways
iterdir()lists one folder;glob("*.txt")matches patterns there;rglob("*.txt")searches every level.os.walkgives each folder with its sub-folders and files.- Filter with
is_file(),suffixandstat().st_size; count withCounter. shutilcopies (copy,copytree), moves (move) and deletes whole trees (rmtree, permanent).tempfile.TemporaryDirectory()makes a folder that cleans itself up.- Sort results and test bulk changes on copies.
Practice
1. Which call lists every .py file at any depth under project?
Show answer
Path("project").rglob("*.py")
2. What is the difference between glob("*.md") and rglob("*.md")?
Show answer
glob("*.md") looks only in that folder; rglob("*.md") searches it and all sub-folders.
3. Count the files (not folders) directly in a folder d.
Show answer
sum(1 for p in d.iterdir() if p.is_file())
4. Which function copies a whole folder, and what happens if the destination exists?
Show answer
shutil.copytree(src, dst). If dst exists it raises FileExistsError unless you pass dirs_exist_ok=True.
5. Why is shutil.rmtree dangerous?
Show answer
It deletes the folder and everything inside it permanently, with no recycle bin, so a wrong path loses data.
6. Why should you sort the result of iterdir() or rglob() when printing?
Show answer
The order is not guaranteed and may differ between systems or runs.