basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    Files and paths: pathlib, reading, writing and walking folders

    The pathlib module joins paths with / the same way on Windows, Linux and macOS, and with open reads and writes files while closing them automatically. Parse a web server log: filter errors, write a report to a separate file and walk a directory tree.

    New herePaths: pathlibReading a file: with open

    What you’ll get

    A folder holds a snippet of a web server log, access.log:

    203.0.113.10 GET / 200 1240
    198.51.100.7 GET /wp-login.php 404 153
    203.0.113.10 GET /en/python/ 200 8420
    203.0.113.24 POST /api/sync 500 89
    198.51.100.7 GET /.env 404 153

    Read the log line by line, pick out lines with status 404 or 500, and write them to errors.log:

    # filter_log.py
    from pathlib import Path
    
    src = Path("access.log")
    dst = Path("errors.log")
    
    errors = []
    with open(src, encoding="utf-8") as f:
        for line in f:
            if " 500 " in line or " 404 " in line:
                errors.append(line)
    
    dst.write_text("".join(errors), encoding="utf-8")
    print("Errors found:", len(errors))
    python filter_log.py
    # Errors found: 3

    errors.log appears in the same folder with the three error lines, while access.log stays untouched. open() accepts a Path object directly — no need to convert it to a string.

    What will it print?
    from pathlib import Path
    
    p = Path("logs") / "2026-11-21" / "access.log"
    print(p.name)
    print(p.stem, p.suffix)
    What will it print?
    Answer:
    access.log
    access .log

    Path never touches the disk until you open the file or call exists(). suffix includes the dot — .log — and stem is the name without the last extension.

    How it works: paths are objects, files must close

    Gluing paths as strings (folder + "/" + name) trips over separators (\ on Windows, / on Linux) and double slashes. In pathlib, a path is a Path object, and the / operator joins parts for the current operating system.

    Path("/var/log/nginx/access.log")
     ├── .parent  ──► /var/log/nginx
     ├── .name    ──► access.log
     ├── .stem    ──► access
     └── .suffix  ──► .log

    Python resolves a relative path like Path("access.log") from the terminal’s current working directory (Path.cwd()), not from the folder where the script lives. If you run python scripts/filter_log.py from your home directory, a file sitting next to the script won’t be found. To anchor paths to the script itself, start from __file__:

    BASE = Path(__file__).parent
    src = BASE / "access.log"

    When Python opens a file, the OS hands out a file descriptor and buffers written data in memory before flushing it to disk. If you open a file without with and forget f.close() — or if the script crashes mid-way — buffered data may never hit disk, and on Windows the file stays locked. with open(...) as f: guarantees Python closes the file as soon as execution leaves the indented block, even on an exception.

    Reading and writing files

    For a small text file, read_text reads the whole thing at once and write_text overwrites it:

    text = Path("access.log").read_text(encoding="utf-8")
    Path("copy.log").write_text(text, encoding="utf-8")

    For a file hundreds of megabytes large, loading it all into memory is wasteful — open it with with open and iterate with for line in f:. Python streams lines from disk as you read. Each line keeps its trailing newline "\n", so strip it before comparing or printing with line.rstrip("\n") or line.strip().

    The second argument to open() sets the mode:

    Mode What it does
    "r" read text (default); missing file raises FileNotFoundError
    "w" write text from scratch: creates the file or erases previous contents
    "a" append to the end: creates the file, leaves existing lines intact
    "rb", "wb" read and write raw bytes, no encoding: images, archives, hashing (Duplicates)

    Always pass encoding="utf-8" for text modes. Python 3.15 made UTF-8 the default on Windows too, but Python 3.14 and older open files in the system locale encoding (cp1251 or cp1252), where non-ASCII text breaks or raises UnicodeDecodeError. An explicit encoding="utf-8" behaves the same on every version.

    Folders: check, create, walk

    Path methods cover everyday folder work without third-party libraries:

    Task Code
    check if it exists on disk p.exists()
    tell a file from a folder p.is_file(), p.is_dir()
    create a folder (and parents) p.mkdir(parents=True, exist_ok=True)
    list contents one level deep for item in p.iterdir():
    match a pattern in one folder p.glob("*.log")
    match a pattern across all subfolders p.rglob("*.log")
    get file size in bytes p.stat().st_size
    rename or move p.rename(target)

    Sum the sizes of all .log files inside logs and its subdirectories:

    from pathlib import Path
    
    total = 0
    for path in Path("logs").rglob("*.log"):
        if path.is_file():
            total += path.stat().st_size
    
    print("Total bytes:", total)

    Checking path.is_file() guards against the edge case of a directory with a dot in its name, such as old.log. The same iterdir and rglob traversal drives Sort Downloads and What takes up space.

    Take it further

    Number the lines of notes.txt and write the result to numbered.txt (1: …, 2: …)

    One with statement can open two files separated by a comma; enumerate(src_f, start=1) numbers from 1.

    with open("notes.txt", encoding="utf-8") as src_f, open("numbered.txt", "w", encoding="utf-8") as dst_f:
        for n, line in enumerate(src_f, start=1):
            dst_f.write(f"{n}: {line}")
    Count how many files of each extension live in the current folder (no subfolders)

    Walk Path(".").iterdir(), skip folders with item.is_file(), get the extension with item.suffix.lower() and tally in a dict.

    from pathlib import Path
    
    counts = {}
    for item in Path(".").iterdir():
        if item.is_file():
            ext = item.suffix.lower() or "(no extension)"
            counts[ext] = counts.get(ext, 0) + 1
    
    print(counts)
    Append a dated line to the end of journal.txt without erasing old entries

    Use mode "a" and end the string with \n — write() does not add a newline on its own.

    with open("journal.txt", "a", encoding="utf-8") as f:
        f.write("2026-11-21: updated packages\n")

    If it doesn’t work

    FileNotFoundError: [Errno 2] No such file or directory: 'access.log'

    Cause
    A relative path resolves from the terminal’s current working directory (Path.cwd()), not the script’s folder — or there is a typo in the filename.
    Fix
    Switch to the right folder with cd, or anchor the path to the script file itself: Path(__file__).parent / "access.log".

    UnicodeDecodeError: 'utf-8' codec can't decode byte 0xef in position 0: invalid continuation byte

    Cause
    The file isn’t saved as UTF-8, but in another encoding — such as Windows-1251 (cp1251) from an older program or Notepad.
    Fix
    Pass the matching encoding when reading: encoding="cp1251", or re-save the file as UTF-8.

    PermissionError: [Errno 13] Permission denied: 'logs' (on Linux — IsADirectoryError)

    Cause
    You passed a folder path to open() instead of a file, or your user lacks read/write permissions.
    Fix
    Check path.is_file() before opening — iterdir() and rglob() return subdirectories too.

    FileExistsError when calling Path("reports").mkdir()

    Cause
    The folder already exists, and without exist_ok=True, mkdir() raises an error.
    Fix
    Write Path("reports").mkdir(parents=True, exist_ok=True) — it creates missing parent folders and stays quiet if the folder is already there.

    Opened a file in "w" mode and its previous contents vanished

    Cause
    Mode "w" truncates an existing file right on open, before the first write.
    Fix
    Use mode "a" to append to the end. When overwriting files, test the script on a copy first.

    Also in this chapter