Back to Explore
GuideVibeFix editorialUpdated Nov 26, 2026

Python pathlib in Practice: Batch Renaming, Classifying, and Counting Files

Python 3.12.3, zero packages: 12 files created; glob counts .txt 4, .md 4, .log 3, .csv 1, rglob counts .txt 6; 3 files renamed, 12 classified and moved; 1171 bytes, 110 lines, largest file app.log 220 bytes; 0 files left in inbox.

Real photograph of a woman sorting colourful tabbed folders on a wooden desk (illustrative photo)

1. Files pile up fast: why you need pathlib

Sooner or later every programmer hits the same kind of chore: a download folder with hundreds of files, names old and new, suffixes all mixed together; logs generated daily in one directory that should be archived by month; exported reports whose filenames have no year prefix, so sorting them is a mess. The work itself is not hard. What is hard is that doing it with plain strings is wordy and error-prone: joining paths means worrying about slashes, os.path means remembering a pile of function names, and splitting, joining, and checking suffixes each get written differently, so the code grows long and one missing slash means the file is not found.

pathlib is the standard-library module for paths, added in Python 3.4, with zero third-party packages to install. Its core idea is simple: a path stops being a string and becomes an object. Given a Path object, you can ask it directly for its name, its suffix, its parent, and whether it exists, and you can also ask it to create directories, read and write files, and rename or move things. Joining paths needs no plus signs or slashes, just the slash operator: Path("/tmp") / "inbox" / "report-jan.txt". It reads like the directory structure itself, and it is hard to drop a separator by accident.

This guide covers one thing only: using pathlib to batch-process a set of real files, from creating them, through counting, renaming, classifying, and counting bytes. Every step was actually run on this machine. The demo script is demo256_g2.py, zero third-party packages, and it builds a demo directory from scratch under /tmp/pathlib256_demo, wiping the old directory before every run, so the numbers are deterministic: run it yourself and you will get exactly the same results.

2. Demo environment and the headline numbers

Environment and results first, so you can tell whether your reproduction matches. This machine runs Python 3.12.3, and pathlib ships with the standard library, so no pip install is needed. The demo creates 12 files in an inbox directory, plus 2 old files in an inbox/archive subdirectory that are never touched, so 14 files are involved in total. The suffix breakdown of the 12 files is: .txt 4, .md 4, .log 3, .csv 1. Batch renaming changed 3 files, and classifying by suffix moved 12 files. The 12 files add up to 1171 bytes in total, with 110 lines altogether, and the largest single file is app.log at 220 bytes. When the demo ends, 0 files are left in inbox, and the 2 old files in the archive subdirectory are untouched.

The chart below shows the suffix distribution counted in the demo: four suffixes on the horizontal axis, file counts on the vertical axis, with the total bytes and total lines in the caption. The numbers match the demo transcript exactly.

Bar chart: suffix distribution counted by glob, .txt 4, .md 4, .log 3, .csv 1; the 12 files total 1171 bytes and 110 lines, and the largest file app.log is 220 bytes

Reproducing it takes one command: python3 demo256_g2.py --lang en, or --lang zh for the Chinese version. Both runs exit with code 0, and the Chinese and English transcripts agree on every number apart from the language labels. The demo only creates files under /tmp and never touches any existing file on your machine; you can delete the whole demo directory afterwards.

3. Path is an object, not a string

Look at the line printed by section 0 of the demo: the sample path is inbox/report-jan.txt, its name is report-jan.txt, its suffix is .txt, its stem is report-jan, its parent is named inbox, and asking exists before creation returns False. Those five attributes plus one method are the most common way to take a path apart. name is the final component including the suffix; stem is the name with the last suffix removed; suffix is the part after the last dot, dot included; parent is the path with the last component removed.

One detail is worth remembering: stem removes only the last suffix. The official documentation uses /srv/holy/grail.tar.gz as its example: its stem is grail.tar and its suffix is .gz, not .tar.gz. The demo file report-jan.txt has a single suffix, so its stem is simply report-jan. When you meet a double-suffixed file such as .tar.gz later, remember that suffix only recognises the final segment, and do not assume otherwise when classifying files.

The fact that exists returns False is not an error; it is just answering a question: does this path exist right now? pathlib keeps questions and actions strictly apart: exists, is_file, and is_dir only ask, while creating, renaming, and deleting actually do something. That split is friendly to batch scripts: you can finish all the checks and list every file you intend to touch before changing anything, and stop at any step that looks wrong.

A Path object has one more habit: it is immutable, so an operation never changes it in place but returns a new Path object instead. with_name returns a new path with the filename replaced, with_suffix returns a new path with the suffix replaced, and the original object stays untouched. Section 6 of the demo works exactly this way: it takes the path of the Chinese-named file, uses with_name to compute the renamed path, and only then calls rename to do the real work. Once you understand this, you will not be surprised that p itself is unchanged after p / "a.txt".

4. Creating files: mkdir and write_text

Section 1 of the demo creates 12 files at once, with hard-coded content whose line counts and byte counts can be worked out in advance. Directories come first: archive.mkdir(parents=True), where parents=True means missing parent directories are created along the way, so inbox is created together with archive instead of one level at a time. The sorted directory is created with a plain mkdir because its parent, the demo root, already exists. Creating a directory that already exists raises an error unless you add exist_ok=True, and section 4 relies on exactly that when classifying: the first .txt file creates sorted/txt, and the next 3 .txt files ask for the same directory again, which is simply skipped.

Files are written with write_text and read with read_text, both with the encoding written out explicitly as utf-8. Writing the encoding out is a good habit: without it Python falls back to the system default, which can differ between machines, and Chinese content in particular is liable to turn into mojibake when you move machines. write_text writes the whole file at once and overwrites it if it already exists; read_text reads the whole file into one string. Both fit small files: the largest of the 12 demo files is only 220 bytes, so reading it into memory is no burden at all. Large files should not be read this way, and the statistics section below covers the alternative.

The 12 files are distributed as follows: 4 .txt files, the three monthly reports report-jan.txt, report-feb.txt, and report-mar.txt plus notes.txt; 4 .md files, draft.md, readme.md, guide.md, and changelog.md; 3 .log files, app.log, error.log, and debug.log; and 1 .csv file, data.csv. A monthly report is a line such as January report repeated 8 times, and a log is a line such as INFO start repeated 20 times, so every line count and byte count can be checked by hand. After creating them, the demo counts once: 12 files were created directly in inbox, and with the 2 old files old-01.txt and old-02.txt in the archive subdirectory, the total is 14.

5. glob vs rglob: settle the scope before you count

Once the files exist, the first job is to count them. Section 2 of the demo counts by suffix with glob, four times: inbox.glob("*.txt") finds 4, inbox.glob("*.md") finds 4, inbox.glob("*.log") finds 3, and inbox.glob("*.csv") finds 1. glob looks at the current directory only and never descends into subdirectories, so the 2 old .txt files in archive are not counted. To include subdirectories, use rglob: inbox.rglob("*.txt") returns 6, exactly the 4 plus the 2 in archive.

The difference between glob and rglob is one sentence: glob sees one level, rglob recurses through everything. The official documentation makes the same point: Path(".").glob("**/*.py"), with the double star, is equivalent to rglob("*.py"), both matching recursively. In real scripts, decide whether you want subdirectories before choosing the method. Use rglob when you only wanted the current level and files in subdirectories get changed together; use glob when you wanted recursion and files in subdirectories get missed. The demo numbers, 4 versus 6, differ by exactly the 2 old files in archive, and counting before you act tells you whether the scope is what you intended.

The wildcards themselves deserve a sentence: the star * matches any number of characters but never crosses a directory separator; the question mark ? matches exactly one character; square brackets such as [0-9] match one character from the set. The demo uses only the simplest form, *.txt, which is enough for everyday batch work. For fancier rules, such as filtering filenames by a date range, filter the glob results with a regular expression instead of forcing the expression into the wildcard pattern.

One more trap is easy to walk into: glob returns a generator, not a list. The demo always turns it into a list with len(list(...)) before counting. A generator can only be consumed once; count it and it is gone, so looping over it a second time gives you nothing. In a batch script, whenever a result will be used more than once, store list() of it first. That habit saves a lot of mysterious empty results.

6. Batch renaming: 3 files, names only, contents untouched

Section 3 of the demo renames the 3 monthly report files: report-jan.txt becomes 2026-report-jan.txt, report-feb.txt becomes 2026-report-feb.txt, and report-mar.txt becomes 2026-report-mar.txt, a total of 3 renames. The code finds the files with inbox.glob("report-*.txt"), sorts them, then computes each new name with with_name and applies it with rename.

for old in sorted(inbox.glob("report-*.txt")):
    new = old.with_name("2026-" + old.name)
    old.rename(new)

Three things in this snippet are worth pulling apart. First, sorted is essential: glob does not promise alphabetical order, so renaming without sorting could run in a different order on each run, which makes failures hard to reproduce. Sorting before any batch operation is a favour to your future self. Second, with_name only computes the new path; rename does the actual work. Computing the name and changing the name are two steps, so you can print the plan and check it before executing, and the demo does exactly that, printing report-jan.txt -> 2026-report-jan.txt as its example. Third, rename inside one directory is a rename, while rename across directories is a move; section 7 classifies files with the very same method, only with a different destination directory.

Before renaming, think about whether the target name might collide with a file that already exists. On POSIX systems, rename overwrites the existing file without asking; on Windows it raises an error. That difference lives at the operating-system level, and the demo only ran on this Linux machine, so the overwrite behaviour was not measured here. Do not rely on either default when writing cross-platform scripts. The safe approach is to check whether the target path exists before renaming, and skip it or pick another name, rather than letting the system decide for you.

7. Classifying by suffix: 12 files into sorted/

Section 4 of the demo is the part that most resembles everyday work: move the 12 files in inbox into four directories by suffix, sorted/txt, sorted/md, sorted/log, and sorted/csv. The number of files moved is 12, and after the move the four directories hold 4, 4, 3, and 1 files respectively, matching the suffix distribution counted in section 2 exactly. Counting again after the move is the cheapest self-check you can do: .txt was 4 before the move and sorted/txt holds 4 after it, so nothing was lost or misplaced.

for f in sorted(inbox.glob("*")):
    if not f.is_file():
        continue
    dest_dir = sorted_dir / f.suffix.lstrip(".")
    dest_dir.mkdir(exist_ok=True)
    f.rename(dest_dir / f.name)

Two checks are hiding in this code. The first is is_file: inbox.glob("*") lists the archive subdirectory as well, and a directory cannot be renamed into sorted/txt, so is_file filters directories out first. The 2 old files in archive survive the whole demo untouched because of that one line. The second is suffix.lstrip("."): suffix carries a dot, .txt, and the directory name does not want it, so lstrip(".") strips it to give txt, which is then joined into sorted/txt. lstrip removes all leading dot characters, and a normal suffix has exactly one dot, so that is enough.

mkdir(exist_ok=True) is required here: the classifying loop has to make sure the destination directory exists for every file it meets, so the first .txt file creates sorted/txt and the following 3 .txt files ask for the same directory again, which would raise an error without exist_ok=True. After classifying, the demo checks inbox once more: the number of files left is 0. Note that this 0 counts only files directly in inbox; the archive subdirectory is still there, and its 2 old files were never touched. Counting the current level versus recursing is the same distinction as glob versus rglob above.

8. Reading files, counting lines, totalling bytes

Section 5 of the demo reads the 12 files again and produces statistics: the total is 1171 bytes, the total line count is 110, and the largest file is app.log at 220 bytes. Byte totals come from read_bytes measured with len, line counts from read_text split with splitlines. Bytes and lines are two different things: one Chinese character takes 3 bytes in UTF-8, while a line count only counts newline characters, and although the demo files are all English, so bytes can be worked out by counting characters, that does not hold for Chinese files, as the Chinese filename example in the next section shows.

The total of 1171 can be verified by hand: the 4 .txt files add up to 417 bytes, the 4 .md files to 222 bytes, the 3 .log files to 472 bytes, and the 1 .csv file to 60 bytes, and 417 plus 222 plus 472 plus 60 is exactly 1171. The 110 lines break down the same way: 29 lines in .txt files, 24 in .md files, 47 in .log files, and 10 in the .csv file, adding up to 110. The largest file, app.log, is the line INFO start repeated 20 times, 11 bytes per line, and 20 times 11 is 220 bytes. The demo script does not hard-code any of these numbers; it recomputes them on every run, and the fact that the recomputed numbers match the hand calculation is what shows the reading and counting logic is correct.

Pay attention to how each quantity is read: read_bytes returns a bytes object, so len measures bytes; read_text returns a string, so len measures characters. The demo uses both, with the 1171 bytes computed from read_bytes and the line count from splitlines on read_text. splitlines does not count a trailing empty string as a line, so for a file where every line ends with a newline, the line count equals the number of newline characters. If the last line has no trailing newline, the two differ by one, which is a boundary worth remembering in any statistics script.

Do not read a large file into memory in one go with read_text. The demo files are tiny, so reading them whole is fine; faced with a log file of several hundred megabytes, the right approach is to read line by line, or read_bytes in chunks. pathlib's open method is the same as the built-in open: use with path.open(encoding="utf-8") as f and process it line by line, and memory usage stays at roughly one line. That pattern was not run in the demo; it is standard-library practice, and it is the approach to use when writing scripts for large files.

9. Edge cases: Chinese filenames, missing files, changing suffixes

Section 6 of the demo handles three edge cases on purpose. The first is a Chinese filename: it creates a file in inbox whose name is the four Chinese characters for "meeting minutes" with a .txt suffix, its content the Chinese phrase for "meeting notes" repeated 3 times, then renames it with with_name to add a 2026- prefix. (The exact characters appear in the demo transcript; this English text describes them in words so the body stays ASCII-only.) After the rename it checks: the stem is the prefixed Chinese name, the suffix is .txt, and exists is True. Chinese filenames need no special handling in pathlib; a Path object simply holds a string, and as long as the encoding is written as utf-8 when reading and writing, everything works. The demo also computes one more name with with_suffix, the same name with a .md suffix, without applying it, to show how a suffix change is written.

The second case is a missing file: asking exists for a file that does not exist — its name is the Chinese phrase for "a file that does not exist" with a .txt suffix — returns False. That check looks trivial, but in batch scripts it is the most common gatekeeper: check existence before processing, skip the file and log a line if it is absent, instead of waiting for the open call to raise an exception. The difference between exists and is_file matters too: exists only asks whether something is there, file or directory; is_file also requires it to be a file. When a path is a directory, exists is True and is_file is False, and the classifying loop in section 7 relies on is_file to keep the archive directory out.

The third case is a relative path: relative_to converts a full path into a path relative to a given directory. In the demo, the renamed Chinese file relative to the demo root is inbox/ followed by the renamed filename, with the 2026- prefix and the .txt suffix. Relative paths read more cleanly in logs than absolute ones, and they are easier to compare across machines. Note that relative_to requires the target to actually sit under the base directory; otherwise it raises ValueError instead of quietly returning a result containing ... For a relative path that is allowed to contain .., os.path.relpath is the right tool, so do not mix the two up.

After the edge cases, the demo deletes the Chinese file to clean up, and the number of files left in inbox is 0. That 0 means the same as the 0 after section 4: the current level is empty, while the archive subdirectory and its 2 old files are still there. Cleanup uses unlink for files, rmdir for directories, and shutil.rmtree for a whole directory tree; the demo begins by using shutil.rmtree to wipe the previous demo directory and rebuild it. pathlib itself has no method to delete a directory tree recursively; that job is deliberately left to shutil.

10. Five common pitfalls, read before writing a batch script

The first pitfall is joining paths with strings. Writing base + "/" + name works on Linux and breaks on Windows, where the separator is a backslash. pathlib's slash operator picks the separator for the current system automatically, so the same code runs on both. If you already have a pile of string paths, wrap them with Path(s) to turn them into objects and enjoy the object methods, instead of converting back and forth between strings and objects.

The second pitfall is using glob where you meant rglob, or the other way round. Use rglob when you only wanted the current level and files in subdirectories get changed as well; use glob when you wanted recursion and files in subdirectories get missed. The demo numbers, 4 versus 6, are the perfect reminder: count before you act, and confirm the scope is what you intended. Batch renames and moves cannot be undone, and counting costs nothing, while fixing a mistake costs a trip to your backups.

The third pitfall is running a batch operation without sorting. glob does not promise an order, so the same code can run in a different order on different runs. The demo sorts before both renaming and classifying, so the output order is stable. Sorting has a second benefit: when something goes wrong and you compare against the log, filenames in alphabetical order are much quicker to search.

The fourth pitfall is reading a file without writing the encoding. Without an encoding argument, read_text falls back to the system default, usually UTF-8 on Linux but possibly something else on Windows, and Chinese content turns into mojibake as soon as you change machines. The demo writes encoding="utf-8" on every read and write; a dozen extra characters that save a cross-platform bug. The same applies to write_text: do not skip its encoding argument either.

The fifth pitfall is confusing PurePath with Path. The official documentation splits path classes into two groups: pure paths only compute and never touch the disk, for example when manipulating Windows-style paths on Linux, while concrete paths can also read and write files. For everyday batch work, use Path directly; the documentation itself says that if you are unsure which class to use, Path is most likely what you need. Only reach for PurePath, PurePosixPath, or PureWindowsPath when you explicitly want to compute paths without touching the disk.

11. Reproduction steps and a checklist

Reproducing the demo in this guide takes three steps. First, check the Python version: python3 --version, which is Python 3.12.3 on this machine; pathlib is in the standard library and has been there since Python 3.4, so nothing needs installing with pip. Second, run the demo script: python3 demo256_g2.py --lang en, which exits with code 0 and prints the results of 7 short sections in the English transcript. Third, compare the numbers: 12 files; suffix counts of 4, 4, 3, and 1; rglob counting 6 .txt files; 3 renames; 12 files classified and moved; a total of 1171 bytes; 110 lines in total; the largest file app.log at 220 bytes; 0 files left in inbox at the end; and the 2 old files in archive untouched. If every number matches, the demo produced the same result on your machine.

Before writing your own batch script, run through this checklist: count the files with glob first and confirm whether the scope is the current level or recursive; compute the target names and print them for checking before renaming or moving, to confirm there is no collision that would overwrite a file; count again after classifying and confirm each directory holds the same number as before the move; keep read_bytes and read_text apart when counting bytes and lines; write utf-8 explicitly for every Chinese filename and every piece of Chinese content; and at the end, confirm the source directory is empty and the destination directories gained the corresponding files. Every item on this list has a matching number in the demo to compare against.

Some things in this guide are written from the official documentation and were not measured in the demo, and that boundary is stated plainly. The behaviour of rename overwriting an existing target on POSIX systems and raising an error on Windows was not measured; do not rely on it when writing cross-platform scripts. The line-by-line reading pattern for large files was not run in the demo; it is standard-library practice. The use of PurePath for computing paths without touching the disk was not demonstrated; Path is enough for everyday work. Symbolic links were not covered either; how resolve handles .. components and link resolution follows the documentation, so think about whether to follow links before stepping into a directory that contains them. None of these points has a corresponding number in the demo transcript, and the text does not claim they were measured.

pathlib can do more than this guide covers: stat shows file size and modification time, touch creates an empty file, chmod changes permissions, iterdir walks a directory, and match tests a filename against a pattern. But batch file work comes down to four actions: find the files, change their names, move them to the right place, and read them to compute something. Practise those four actions, and the usual messes in download folders, log folders, and export folders can be tidied with a dozen lines of script; count once before running and once after, and the chance of a mistake drops sharply.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles