{"id":30776,"date":"2026-12-03T22:04:05","date_gmt":"2026-12-03T22:04:05","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=30776"},"modified":"2026-12-03T22:04:05","modified_gmt":"2026-12-03T22:04:05","slug":"python-tutorials-files-operations","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/python-tutorials-files-operations\/","title":{"rendered":"Python Tutorials: Files Operations"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Python handles files through the built-in <code>open()<\/code> function. The mode you pass to it decides whether you create, read, append to or overwrite a file, and <code>os.remove()<\/code> or <code>pathlib<\/code> deletes it. This page explains the modes shown in the diagrams above and gives a corrected, runnable version of the CRUD and JSON example code. It also covers the errors you are most likely to hit.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Python File Operations<\/h2>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<figure class=\"wp-block-image size-full\"><a href=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-file-operations.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1400\" height=\"1094\" src=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-file-operations.png\" alt=\"Python file operations mind map: paths, open, read, write, search, file pointer, status, copy, move and delete\" class=\"wp-image-31574\" srcset=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-file-operations.png 1400w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-file-operations-300x234.png 300w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-file-operations-1024x800.png 1024w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-file-operations-768x600.png 768w\" sizes=\"auto, (max-width: 1400px) 100vw, 1400px\" \/><\/a><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Python &#8211; Working with files<\/h2>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"403\" src=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-working-with-files-1024x403.png\" alt=\"Working with files in Python: os module, urllib downloads, and reading and writing with open()\" class=\"wp-image-31585\" srcset=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-working-with-files-1024x403.png 1024w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-working-with-files-300x118.png 300w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-working-with-files-768x302.png 768w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-working-with-files-1536x604.png 1536w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-working-with-files-2048x806.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Python File Operations: Modes<\/h2>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"585\" height=\"553\" src=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/image-13.png\" alt=\"Python open() function modes: r reads, a appends, w writes and overwrites, x creates a file\" class=\"wp-image-31583\" srcset=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/image-13.png 585w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/image-13-300x284.png 300w\" sizes=\"auto, (max-width: 585px) 100vw, 585px\" \/><\/figure>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"729\" height=\"417\" src=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-file-operations-modes.png\" alt=\"Table of Python file modes w, r, a, w+, r+, a+ and x with descriptions of each behavior\" class=\"wp-image-31579\" srcset=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-file-operations-modes.png 729w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-file-operations-modes-300x172.png 300w\" sizes=\"auto, (max-width: 729px) 100vw, 729px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Python File Operations: Writing a file<\/h2>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"931\" height=\"673\" src=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-file-operations-writing-a-file.jpg\" alt=\"Annotated Python code writing four user-entered names to names.txt in write mode, then closing the file\" class=\"wp-image-31581\" srcset=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-file-operations-writing-a-file.jpg 931w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-file-operations-writing-a-file-300x217.jpg 300w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/10\/python-file-operations-writing-a-file-768x555.jpg 768w\" sizes=\"auto, (max-width: 931px) 100vw, 931px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Python File Operations: CRUD<\/h2>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/20d4e1dac83ac2dec7630de86326cb4a.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">How Python file operations work<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Every file operation follows the same three steps: open the file with <code>open(path, mode)<\/code>, read or write through the returned file object, and close it. Closing matters because writes are buffered. Data may not reach the disk until the buffer is flushed, and an open file handle on Windows stops other processes, and your own script, from deleting or renaming the file.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>with<\/code> statement closes the file automatically, even if an exception is raised. Use it in all new code instead of calling <code>f.close()<\/code> by hand, as most of the gist code above does.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">with open(<span class=\"hljs-string\">\"notes.txt\"<\/span>, <span class=\"hljs-string\">\"w\"<\/span>, encoding=<span class=\"hljs-string\">\"utf-8\"<\/span>) <span class=\"hljs-keyword\">as<\/span> f:\n    f.write(<span class=\"hljs-string\">\"hello\\n\"<\/span>)\n<span class=\"hljs-comment\"># f is closed here, and the data is flushed to disk<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Always pass <code>encoding=&quot;utf-8&quot;<\/code> when you open a file in text mode. Without it, Python uses the platform&#039;s default encoding, so the same script can read a file correctly on Linux and fail with <code>UnicodeDecodeError<\/code> on Windows.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">File modes reference<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Mode<\/th><th>Meaning<\/th><th>If file exists<\/th><th>If file is missing<\/th><\/tr><\/thead><tbody><tr><td><code>r<\/code><\/td><td>Read (default)<\/td><td>Reads from the start<\/td><td><code>FileNotFoundError<\/code><\/td><\/tr><tr><td><code>w<\/code><\/td><td>Write<\/td><td><strong>Truncates<\/strong> it to zero length<\/td><td>Creates it<\/td><\/tr><tr><td><code>a<\/code><\/td><td>Append<\/td><td>Writes go to the end<\/td><td>Creates it<\/td><\/tr><tr><td><code>x<\/code><\/td><td>Exclusive create<\/td><td><code>FileExistsError<\/code><\/td><td>Creates it<\/td><\/tr><tr><td><code>r+<\/code><\/td><td>Read and write<\/td><td>Opens without truncating<\/td><td><code>FileNotFoundError<\/code><\/td><\/tr><tr><td><code>w+<\/code><\/td><td>Write and read<\/td><td>Truncates it<\/td><td>Creates it<\/td><\/tr><tr><td><code>a+<\/code><\/td><td>Append and read<\/td><td>Writes go to the end<\/td><td>Creates it<\/td><\/tr><tr><td><code>b<\/code><\/td><td>Binary, combined with the above (for example <code>rb<\/code>, <code>wb<\/code>)<\/td><td>Works with <code>bytes<\/code>, no encoding<\/td><td>Same as the base mode<\/td><\/tr><tr><td><code>t<\/code><\/td><td>Text (default), for example <code>rt<\/code><\/td><td>Works with <code>str<\/code><\/td><td>Same as the base mode<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> <code>w<\/code> never asks for confirmation. Opening an existing file in <code>w<\/code> mode wipes its contents immediately, even if you never call <code>write()<\/code>. Use <code>x<\/code> when you must not overwrite existing data.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Corrected CRUD example<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The script below does the same create, read, update and delete steps as <code>crud-file.py<\/code> above. It runs cleanly from start to finish and can be run again without failing.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import os\n\nos.makedirs(<span class=\"hljs-string\">\"live\"<\/span>, exist_ok=<span class=\"hljs-keyword\">True<\/span>)          <span class=\"hljs-comment\"># make sure the folder exists<\/span>\ntarget = os.path.join(<span class=\"hljs-string\">\"live\"<\/span>, <span class=\"hljs-string\">\"createfile.txt\"<\/span>)\n\n<span class=\"hljs-comment\"># CREATE: 'x' refuses to overwrite an existing file<\/span>\n<span class=\"hljs-keyword\">try<\/span>:\n    with open(target, <span class=\"hljs-string\">\"x\"<\/span>, encoding=<span class=\"hljs-string\">\"utf-8\"<\/span>) <span class=\"hljs-keyword\">as<\/span> f:\n        f.write(<span class=\"hljs-string\">\"First line.\\n\"<\/span>)\nexcept FileExistsError:\n    <span class=\"hljs-keyword\">print<\/span>(f<span class=\"hljs-string\">\"{target} already exists, skipping create\"<\/span>)\n\n<span class=\"hljs-comment\"># READ<\/span>\nwith open(target, <span class=\"hljs-string\">\"r\"<\/span>, encoding=<span class=\"hljs-string\">\"utf-8\"<\/span>) <span class=\"hljs-keyword\">as<\/span> f:\n    <span class=\"hljs-keyword\">print<\/span>(f.read())\n\n<span class=\"hljs-comment\"># UPDATE (append): adds to the end<\/span>\nwith open(target, <span class=\"hljs-string\">\"a\"<\/span>, encoding=<span class=\"hljs-string\">\"utf-8\"<\/span>) <span class=\"hljs-keyword\">as<\/span> f:\n    f.write(<span class=\"hljs-string\">\"Append this text.\\n\"<\/span>)\n\n<span class=\"hljs-comment\"># UPDATE (overwrite): replaces everything<\/span>\nwith open(target, <span class=\"hljs-string\">\"w\"<\/span>, encoding=<span class=\"hljs-string\">\"utf-8\"<\/span>) <span class=\"hljs-keyword\">as<\/span> f:\n    f.write(<span class=\"hljs-string\">\"Overwrite existing data.\\n\"<\/span>)\n\nwith open(target, encoding=<span class=\"hljs-string\">\"utf-8\"<\/span>) <span class=\"hljs-keyword\">as<\/span> f:\n    <span class=\"hljs-keyword\">print<\/span>(f.read())\n\n<span class=\"hljs-comment\"># DELETE: safe because every handle is already closed<\/span>\nos.remove(target)\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"Exists after delete:\"<\/span>, os.path.exists(target))<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Expected output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">First line.\n\nOverwrite existing data.\n\nExists after <span class=\"hljs-keyword\">delete<\/span>: False<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The blank lines appear because each file ends with <code>\\n<\/code> and <code>print()<\/code> adds a second newline. To print without the extra line, use <code>print(f.read(), end=&quot;&quot;)<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What was wrong in the original gist code<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>crud-file.py<\/code> calls <code>os.remove()<\/code> but never runs <code>import os<\/code>, so the last line raises <code>NameError: name &#039;os&#039; is not defined<\/code>.<\/li>\n\n\n<li><code>&quot;D:\\\\myfiles\\welcome.txt&quot;<\/code> contains <code>\\w<\/code>, which is an invalid escape sequence. It happens to work, but recent Python versions emit a <code>SyntaxWarning<\/code>. Use a raw string <code>r&quot;D:\\myfiles\\welcome.txt&quot;<\/code> or forward slashes <code>&quot;D:\/myfiles\/welcome.txt&quot;<\/code>.<\/li>\n\n\n<li><code>open(&quot;myfile.txt&quot;, &quot;x&quot;)<\/code> fails with <code>FileExistsError<\/code> the second time you run the script. The comment on the later <code>&quot;w&quot;<\/code> line says it creates a file &quot;if it does not exist&quot;, but it also truncates an existing file.<\/li>\n\n\n<li>Most files are opened and never closed. The last read of <code>live\/createfile.txt<\/code> leaves the handle open before <code>os.remove()<\/code>, which raises <code>PermissionError<\/code> on Windows.<\/li>\n\n\n<li>The comment above the <code>demofile3.txt<\/code> read says &quot;after the appending&quot;. That file was overwritten with <code>w<\/code>, not appended to.<\/li>\n\n\n<li><code>f.flush()<\/code> immediately before <code>f.close()<\/code> does nothing extra, because closing a file always flushes it.<\/li>\n\n\n<li><code>live\/createfile.txt<\/code> needs the <code>live<\/code> folder to exist. Mode <code>a<\/code> creates missing files but not missing directories.<\/li>\n\n\n<li>In <code>input.py<\/code>, the variable <code>input<\/code> shadows Python&#039;s built-in <code>input()<\/code> function, and the script carries on even when the existence check says the file is missing.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Reading files efficiently<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><code>f.read()<\/code> loads the whole file into memory. That is fine for small configuration files but a bad idea for multi-gigabyte logs. For those, iterate over the file object, which reads one line at a time:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">with open(<span class=\"hljs-string\">\"app.log\"<\/span>, encoding=<span class=\"hljs-string\">\"utf-8\"<\/span>) <span class=\"hljs-keyword\">as<\/span> f:\n    <span class=\"hljs-keyword\">for<\/span> line in f:                 <span class=\"hljs-comment\"># streams line by line<\/span>\n        <span class=\"hljs-keyword\">if<\/span> <span class=\"hljs-string\">\"ERROR\"<\/span> in line:\n            <span class=\"hljs-keyword\">print<\/span>(line.rstrip())\n\n<span class=\"hljs-comment\"># Other options<\/span>\nwith open(<span class=\"hljs-string\">\"app.log\"<\/span>, encoding=<span class=\"hljs-string\">\"utf-8\"<\/span>) <span class=\"hljs-keyword\">as<\/span> f:\n    first = f.readline()           <span class=\"hljs-comment\"># one line, including the trailing \\n<\/span>\n    rest = f.readlines()           <span class=\"hljs-comment\"># list of remaining lines (loads all into memory)<\/span>\n\n<span class=\"hljs-comment\"># Binary files such as images or archives<\/span>\nwith open(<span class=\"hljs-string\">\"logo.png\"<\/span>, <span class=\"hljs-string\">\"rb\"<\/span>) <span class=\"hljs-keyword\">as<\/span> f:\n    header = f.read(<span class=\"hljs-number\">8<\/span>)             <span class=\"hljs-comment\"># returns bytes<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Checking paths with os and pathlib<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The example above uses <code>os.getcwd()<\/code>, <code>os.listdir()<\/code> and <code>os.path.isfile()<\/code>. The standard-library <code>pathlib<\/code> module does the same jobs with a cleaner, object-oriented API and handles path separators on every operating system:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">from pathlib import Path\n\ncwd = Path.cwd()\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"Files in\"<\/span>, cwd, &#91;p.name <span class=\"hljs-keyword\">for<\/span> p in cwd.iterdir()])\n\np = Path(<span class=\"hljs-string\">\"live\"<\/span>) \/ <span class=\"hljs-string\">\"myfile.txt\"<\/span>   <span class=\"hljs-comment\"># \/ joins paths portably<\/span>\n<span class=\"hljs-keyword\">print<\/span>(p.exists(), p.is_file(), p.is_dir())\n\np.<span class=\"hljs-keyword\">parent<\/span>.mkdir(parents=<span class=\"hljs-keyword\">True<\/span>, exist_ok=<span class=\"hljs-keyword\">True<\/span>)\np.write_text(<span class=\"hljs-string\">\"quick write\\n\"<\/span>, encoding=<span class=\"hljs-string\">\"utf-8\"<\/span>)\n<span class=\"hljs-keyword\">print<\/span>(p.read_text(encoding=<span class=\"hljs-string\">\"utf-8\"<\/span>))\np.unlink(missing_ok=<span class=\"hljs-keyword\">True<\/span>)          <span class=\"hljs-comment\"># delete; no error if already gone<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> Relative paths such as <code>live\/myfile.txt<\/code> are resolved against the current working directory, not the script&#039;s folder. If a script works from your IDE but not from cron or CI, build paths from <code>Path(__file__).resolve().parent<\/code> instead.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Corrected JSON read and write example<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">This version of <code>input.py<\/code> stops if the input file is missing and avoids shadowing built-in names. It produces the same <code>output.txt<\/code>.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import json\nfrom pathlib import Path\n\nsrc = Path(<span class=\"hljs-string\">\"sample-programs\/system\/input.json\"<\/span>)\ndst = src.with_name(<span class=\"hljs-string\">\"output.txt\"<\/span>)\n\n<span class=\"hljs-keyword\">if<\/span> not src.is_file():\n    raise SystemExit(f<span class=\"hljs-string\">\"Input file not found: {src}\"<\/span>)\n\nwith src.open(<span class=\"hljs-string\">\"r\"<\/span>, encoding=<span class=\"hljs-string\">\"utf-8\"<\/span>) <span class=\"hljs-keyword\">as<\/span> infile:\n    data = json.load(infile)           <span class=\"hljs-comment\"># parse JSON into a dict<\/span>\n\nwith dst.open(<span class=\"hljs-string\">\"w\"<\/span>, encoding=<span class=\"hljs-string\">\"utf-8\"<\/span>) <span class=\"hljs-keyword\">as<\/span> outfile:\n    outfile.write(f<span class=\"hljs-string\">\"{data&#91;'name']}'s Hobbies:\\n\"<\/span>)\n    <span class=\"hljs-keyword\">for<\/span> hobby in data&#91;<span class=\"hljs-string\">\"hobbies\"<\/span>]:\n        outfile.write(f<span class=\"hljs-string\">\"{hobby}\\n\"<\/span>)\n\n<span class=\"hljs-comment\"># Writing JSON back out<\/span>\nwith src.with_name(<span class=\"hljs-string\">\"copy.json\"<\/span>).open(<span class=\"hljs-string\">\"w\"<\/span>, encoding=<span class=\"hljs-string\">\"utf-8\"<\/span>) <span class=\"hljs-keyword\">as<\/span> f:\n    json.dump(data, f, indent=<span class=\"hljs-number\">2<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Resulting <code>output.txt<\/code> for the sample <code>input.json<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">Jason's Hobbies:\nmusic\nprogramming\ngames<\/code><\/span><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Common errors and fixes<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Error<\/th><th>Usual cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td><code>FileNotFoundError<\/code><\/td><td>Wrong relative path, or the parent folder is missing<\/td><td>Print <code>os.getcwd()<\/code>, use absolute paths, create folders with <code>mkdir(parents=True, exist_ok=True)<\/code><\/td><\/tr><tr><td><code>FileExistsError<\/code><\/td><td>Mode <code>x<\/code> on a file that already exists<\/td><td>Catch the exception or choose <code>w<\/code>\/<code>a<\/code> deliberately<\/td><\/tr><tr><td><code>PermissionError<\/code><\/td><td>No access rights, or the file is still open (Windows)<\/td><td>Close handles with <code>with<\/code>, check file ownership and permissions<\/td><\/tr><tr><td><code>IsADirectoryError<\/code><\/td><td>The path points to a folder<\/td><td>Check with <code>is_file()<\/code> before opening<\/td><\/tr><tr><td><code>io.UnsupportedOperation: not writable<\/code><\/td><td>Writing to a file opened with <code>r<\/code><\/td><td>Open with <code>w<\/code>, <code>a<\/code> or <code>r+<\/code><\/td><\/tr><tr><td><code>UnicodeDecodeError<\/code><\/td><td>File encoding differs from the default<\/td><td>Pass the correct <code>encoding=<\/code>, or open in <code>rb<\/code> for binary data<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Best practices<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use <code>with<\/code> for every file you open.<\/li>\n\n\n<li>Always set <code>encoding=&quot;utf-8&quot;<\/code> in text mode.<\/li>\n\n\n<li>Prefer <code>pathlib.Path<\/code> over string concatenation for building paths.<\/li>\n\n\n<li>Prefer trying the operation and catching <code>FileNotFoundError<\/code> over checking <code>exists()<\/code> first. Another process can delete the file between your check and your <code>open()<\/code>.<\/li>\n\n\n<li>For important files, write to a temporary file and then call <code>os.replace(tmp, final)<\/code>. The replace is atomic on the same filesystem, so readers never see a half-written file.<\/li>\n\n\n<li>Do not name variables <code>input<\/code>, <code>file<\/code>, <code>open<\/code> or <code>list<\/code>, because doing so hides built-in names.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">For more practice, see the <a href=\"https:\/\/www.devopsschool.com\/blog\/category\/programming\/python-programming-scripting-languages\/\">Python tutorials<\/a>. File handling also comes up often in <a href=\"https:\/\/www.devopsschool.com\/blog\/top-50-python-interview-questions-and-answers\/\">Python interview questions<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is the difference between w and a mode in Python?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>w<\/code> truncates an existing file to empty before writing, and <code>a<\/code> keeps the existing content and adds new data at the end. Both create the file if it does not exist.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I check if a file exists in Python?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>os.path.isfile(path)<\/code> or <code>Path(path).is_file()<\/code> from <code>pathlib<\/code>. When you are about to open the file anyway, it is more reliable to open it directly and catch <code>FileNotFoundError<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I delete a file in Python?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Call <code>os.remove(path)<\/code> or <code>Path(path).unlink()<\/code>. Close any open handles to the file first. Pass <code>missing_ok=True<\/code> to <code>unlink()<\/code> if a missing file should not raise an error.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why should I use with open() instead of open() and close()?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>with<\/code> block closes the file automatically, even if an exception happens partway through. That way buffered data is written and the handle is released.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the difference between r+ and w+?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Both allow reading and writing. <code>r+<\/code> requires the file to exist and keeps its contents. <code>w+<\/code> creates the file or truncates an existing one to empty.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/programming\/python-programming-scripting-languages\/\">More Python tutorials<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/top-50-python-interview-questions-and-answers\/\">Top 50 Python Interview Questions and Answers<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/top-100-interview-questions-for-python\/\">TOP 100+ INTERVIEW QUESTIONS FOR PYTHON:-<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/what-is-pandas-and-use-cases-of-pandas\/\">What is Pandas and use cases of Pandas?<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Python handles files through the built-in open() function. The mode you pass to it decides whether you create, read, append to or overwrite a file, and os.remove()&#8230; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[499],"tags":[26336],"class_list":["post-30776","post","type-post","status-publish","format-standard","hentry","category-python-programming-scripting-languages","tag-crud-operations"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/30776","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=30776"}],"version-history":[{"count":10,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/30776\/revisions"}],"predecessor-version":[{"id":80603,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/30776\/revisions\/80603"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=30776"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=30776"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=30776"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}