[{"data":1,"prerenderedAt":66},["ShallowReactive",2],{"qa-\u002Fpython\u002Fstdlib\u002Ffiles-pathlib":3},{"page":4,"siblings":52,"blog":43},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":12,"path":20,"questions":21,"related":43,"seo":44,"seoDescription":45,"stem":46,"subtopic":47,"topic":48,"topicSlug":49,"updated":50,"__hash__":51},"qa\u002Fpython\u002Fstdlib\u002Ffiles-pathlib.md","Files Pathlib",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md","Python","python",{},true,"\u002Fpython\u002Fstdlib\u002Ffiles-pathlib",[22,27,31,35,39],{"id":23,"difficulty":24,"q":25,"a":26},"with-open","easy","Why open files with the `with` statement?","`with open(...)` uses the file as a **context manager**, which **guarantees the file\nis closed** when the block exits — even if an exception is raised. Without it you\nmust remember to call `.close()` manually, and a crash mid-block leaks the handle.\n\n```python\nwith open(\"data.txt\") as f:      # f.close() is automatic\n    contents = f.read()\n# file is closed here, even on error\n\nf = open(\"data.txt\")             # manual style — fragile\ntry:\n    contents = f.read()\nfinally:\n    f.close()\n```\n\nLeaked handles can exhaust OS file descriptors and leave buffered writes unflushed.\nAlways prefer `with` for any resource that needs cleanup (files, locks, sockets).\n",{"id":28,"difficulty":14,"q":29,"a":30},"lazy-iteration","What is the difference between iterating a file and read()\u002Freadlines()?","A file object is its own **iterator**, yielding **one line at a time** and holding\nonly that line in memory. `read()` loads the **entire file** into a single string,\nand `readlines()` loads **all lines into a list** — both can blow up memory on large\nfiles.\n\n```python\nwith open(\"huge.log\") as f:\n    for line in f:               # lazy — one line in memory at a time\n        process(line)\n\nwith open(\"huge.log\") as f:\n    data = f.read()              # whole file as one string\n    lines = f.readlines()        # whole file as a list of strings\n```\n\nIterating is the idiomatic, memory-safe way to process big files line by line.\nReserve `read()`\u002F`readlines()` for small files where you genuinely need the whole\ncontent at once.\n",{"id":32,"difficulty":14,"q":33,"a":34},"text-binary-mode","What is the difference between text and binary mode, and why specify encoding?","**Text mode** (`\"r\"`, the default) decodes bytes into `str` using an **encoding** and\nnormalizes newlines. **Binary mode** (`\"rb\"`\u002F`\"wb\"`) reads and writes raw `bytes`\nwith no decoding — required for images, archives, or any non-text data. In text\nmode you should pass **`encoding=`** explicitly, because the default is\nplatform-dependent.\n\n```python\nwith open(\"notes.txt\", \"r\", encoding=\"utf-8\") as f:\n    text: str = f.read()         # decoded to str\n\nwith open(\"photo.jpg\", \"rb\") as f:\n    raw: bytes = f.read()        # raw bytes, no decoding\n```\n\nRelying on the default encoding is a classic cross-platform bug (UTF-8 on Linux\u002FMac,\noften a legacy codepage on Windows). Always specify `encoding=\"utf-8\"` for text, and\nuse binary mode for everything that isn't text.\n",{"id":36,"difficulty":14,"q":37,"a":38},"pathlib-vs-os-path","What is pathlib.Path and how does it compare to os.path?","**`pathlib.Path`** is the modern, object-oriented way to handle filesystem paths. A\n`Path` is an object with **methods and operators**, whereas the older **`os.path`**\nmodule is a collection of **string-based functions**. Path's `\u002F` operator joins\nsegments cleanly and works across operating systems.\n\n```python\nfrom pathlib import Path\n\np = Path(\"data\") \u002F \"logs\" \u002F \"app.log\"   # join with \u002F\np.exists()\np.suffix                                 # \".log\"\np.stem                                   # \"app\"\np.read_text(encoding=\"utf-8\")            # one-liner read\n\nimport os.path\nold = os.path.join(\"data\", \"logs\", \"app.log\")\nos.path.exists(old)\n```\n\n`pathlib` is generally preferred for new code: it's more readable and bundles\ncommon operations (`read_text`, `mkdir`, `glob`) as methods. Use `os.path` mainly\nwhen working with existing string-based APIs.\n",{"id":40,"difficulty":14,"q":41,"a":42},"globbing-path-methods","How do you find files with globbing using pathlib?","Use **`Path.glob(pattern)`** for matches in one directory and **`Path.rglob(pattern)`**\n(or `glob(\"**\u002F...\")`) to recurse into subdirectories. Both return a **lazy generator**\nof `Path` objects, where `*` matches any characters and `**` matches directories\nrecursively.\n\n```python\nfrom pathlib import Path\n\nroot = Path(\"project\")\nfor py in root.glob(\"*.py\"):         # top level only\n    print(py.name)\n\nfor py in root.rglob(\"*.py\"):        # all subdirectories too\n    print(py)\n\nroot.mkdir(parents=True, exist_ok=True)  # create dirs safely\n[p.name for p in root.iterdir()]         # list directory contents\n```\n\nOther handy `Path` methods: `iterdir()` (list a directory), `is_file()`\u002F`is_dir()`,\n`mkdir()`, `unlink()` (delete), and `with_suffix()`. Globbing returns generators, so\nwrap in `list(...)` if you need a concrete collection.\n",null,{"description":11},"Python interview questions on open() and the with statement, lazy file iteration, text vs binary mode and encoding, pathlib.Path vs os.path, and globbing.","python\u002Fstdlib\u002Ffiles-pathlib","Files, pathlib & os","Standard Library Essentials","stdlib","2026-06-18","NoZp_VMdm_N8l_uZ9iKq2ZIl7xuq4gVgtZ6dt2hEatE",[53,57,58,62],{"subtopic":54,"path":55,"order":56},"Regular Expressions","\u002Fpython\u002Fstdlib\u002Fregex",1,{"subtopic":47,"path":20,"order":12},{"subtopic":59,"path":60,"order":61},"datetime","\u002Fpython\u002Fstdlib\u002Fdatetime",3,{"subtopic":63,"path":64,"order":65},"JSON, CSV & pickle","\u002Fpython\u002Fstdlib\u002Fserialization",4,1781808681881]