Python offers different file modes for interacting with files, depending on whether you want to read, write, append, or create new files. These modes are passed as strings to the open() function.
open(filename, mode)📖 r – Read Mode
🔍 Purpose:
Opens a file for reading only.
The file must exist, or Python will raise an error.
📌 Syntax:
f = open("example.txt", "r")🧪 Example:
# Assume example.txt contains: Hello World
f = open("example.txt", "r")
print(f.read())
f.close(Hello World⚠️ Note: Raises FileNotFoundError if the file doesn't exist.
✍️ w – Write Mode
🧹 Purpose:
Opens a file for writing.
Overwrites the file if it exists, or creates a new file.
📌 Syntax:
f = open("example.txt", "w")🧪 Example:
f = open("example.txt", "w")
f.write("New content")
f.close()New contentThe contents of example.txt now become:
⚠️ Warning: Existing file content is erased.
➕ a – Append Mode
📄 Purpose:
Opens the file for appending.
Data is written at the end of the file, preserving existing content.
📌 Syntax:
f = open("example.txt", "a")🧪 Example:
f = open("example.txt", "a")
f.write("\\nAppended line")
f.close()If original file had:
New contentIt becomes:
New content
Appended line🛑 x – Exclusive Creation Mode
🚫 Purpose:
Creates a new file. If the file already exists, it raises a FileExistsError.
📌 Syntax:
f = open("newfile.txt", "x")🧪 Example:
f = open("unique.txt", "x")
f.write("This file is newly created.")
f.close()A new file unique.txt is created with:
This file is newly created.⚠️ Note: If unique.txt already exists, Python throws:
FileExistsError: [Errno 17] File exists: 'unique.txt'💾 b – Binary Mode (with r, w, a)
📦 Purpose:
Used when working with binary files like images, videos, or PDFs.
You must combine it with another mode (rb, wb, etc.)
📌 Syntax:
f = open("image.png", "rb") # Read binary
f = open("video.mp4", "wb") # Write binary🧪 Example:
# Copy an image in binary mode
f1 = open("source.png", "rb")
f2 = open("copy.png", "wb")
f2.write(f1.read())
f1.close()
f2.close()⚠️ Note: Always use binary mode when working with non-text files.
A binary copy of source.png is created as copy.png.
<div class="infographic-pyfilemode">
<style>
.infographic-pyfilemode {
--ink: #1a1a1a;
--ink-soft: #5c5c5c;
--paper: #ffffff;
--paper-alt: #f0ece4;
--accent: #2563eb;
--accent-soft:#e3ebfd;
--line: #ddd6c9;
--err: #c0392b; --err-soft: #fbe9e7;
--ok: #1f9d55; --ok-soft: #e3f5ec;
--warn: #b45309; --warn-soft: #fdf0dc;
--mono-font: 'IBM Plex Mono', 'SFMono-Regular', Menlo, monospace;
--display-font: 'Fraunces', Georgia, serif;
--body-font: 'Inter', system-ui, sans-serif;
box-sizing: border-box;
max-width: 720px;
margin: 0 auto;
font-family: var(--body-font);
color: var(--ink);
background: var(--paper);
}
.infographic-pyfilemode[data-theme="dark"] {
--ink: #e8e6e1;
--ink-soft: #9a968c;
--paper: #121212;
--paper-alt: #1e1e26;
--accent: #5b8def;
--accent-soft:#202942;
--line: #2c313d;
--err: #e57373; --err-soft: #3a2222;
--ok: #6fdc8c; --ok-soft: #16342a;
--warn: #e0a458; --warn-soft: #3a2c14;
}
.infographic-pyfilemode *, .infographic-pyfilemode *::before, .infographic-pyfilemode *::after { box-sizing: border-box; }
.infographic-pyfilemode .fm-wrap { padding: 0 clamp(1rem, 4vw, 2rem) 1.5rem; }
.infographic-pyfilemode h1 {
font-family: var(--display-font); font-weight: 600;
font-size: clamp(1.45rem, 5vw, 1.95rem); text-align: center; margin: 1.5rem 0 0.25rem; letter-spacing: -0.01em;
}
.infographic-pyfilemode .fm-sub { text-align: center; color: var(--ink-soft); font-size: 0.85rem; margin: 0 0 1.3rem; }
.infographic-pyfilemode .file-card {
border: 1.5px solid var(--line); border-radius: 8px; overflow: hidden; margin-bottom: 1rem;
}
.infographic-pyfilemode .file-bar {
display: flex; justify-content: space-between; align-items: center;
font-family: var(--mono-font); font-size: 0.75rem; font-weight: 700; color: var(--ink-soft);
background: var(--paper-alt); padding: 0.4rem 0.7rem; border-bottom: 1px solid var(--line);
}
.infographic-pyfilemode .file-status { font-size: 0.68rem; padding: 0.1rem 0.5rem; border-radius: 999px; font-weight: 700; }
.infographic-pyfilemode .file-status.exists { background: var(--ok-soft); color: var(--ok); }
.infographic-pyfilemode .file-status.missing { background: var(--err-soft); color: var(--err); }
.infographic-pyfilemode .file-body {
font-family: var(--mono-font); font-size: 0.82rem; white-space: pre-wrap; padding: 0.7rem 0.85rem;
min-height: 3em; color: var(--ink); transition: background 0.3s;
}
.infographic-pyfilemode .file-body.is-missing { color: var(--ink-soft); font-style: italic; }
.infographic-pyfilemode .file-body.flash-write { animation: fm-flash-write 0.6s ease; }
.infographic-pyfilemode .file-body.flash-append { animation: fm-flash-append 0.6s ease; }
@keyframes fm-flash-write { 0% { background: var(--err-soft); } 100% { background: transparent; } }
@keyframes fm-flash-append { 0% { background: var(--ok-soft); } 100% { background: transparent; } }
.infographic-pyfilemode .file-ctl-row { display: flex; justify-content: center; gap: 0.4rem; margin-bottom: 1rem; }
.infographic-pyfilemode .file-ctl-btn {
font: inherit; font-size: 0.76rem; font-weight: 600; color: var(--ink-soft);
background: var(--paper-alt); border: 1px solid var(--line); padding: 0.35rem 0.7rem; cursor: pointer; border-radius: 999px;
}
.infographic-pyfilemode .mode-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.4rem; margin-bottom: 0.8rem; }
@media (max-width: 480px) { .infographic-pyfilemode .mode-grid { grid-template-columns: repeat(2, 1fr); } }
.infographic-pyfilemode .mode-btn {
font: inherit; font-family: var(--mono-font); font-size: 0.85rem; font-weight: 700;
background: var(--paper-alt); border: 1.5px solid var(--line); color: var(--ink-soft);
padding: 0.5rem 0.4rem; cursor: pointer; border-radius: 6px; text-align: center;
}
.infographic-pyfilemode .mode-btn.is-selected { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); }
.infographic-pyfilemode .mode-desc {
text-align: center; font-size: 0.8rem; color: var(--ink-soft); margin-bottom: 1rem; min-height: 2.2em;
}
.infographic-pyfilemode .mode-desc strong { color: var(--ink); font-family: var(--mono-font); }
.infographic-pyfilemode .write-row { display: flex; justify-content: center; gap: 0.4rem; margin-bottom: 0.9rem; flex-wrap: wrap; }
.infographic-pyfilemode .write-row input {
font-family: var(--mono-font); font-size: 0.82rem; padding: 0.4rem 0.6rem;
border: 1.5px solid var(--line); border-radius: 5px; background: var(--paper-alt); color: var(--ink); width: 220px;
}
.infographic-pyfilemode .write-row input:focus { outline: none; border-color: var(--accent); }
.infographic-pyfilemode .run-row { display: flex; justify-content: center; margin-bottom: 1rem; }
.infographic-pyfilemode .run-btn {
font: inherit; font-family: var(--mono-font); font-size: 0.85rem; font-weight: 700;
background: var(--accent); color: #fff; border: none; border-radius: 999px;
padding: 0.55rem 1.2rem; cursor: pointer;
}
.infographic-pyfilemode .result-box {
text-align: center; font-family: var(--mono-font); font-size: 0.85rem; font-weight: 700;
padding: 0.6rem 0.9rem; border-radius: 8px; border: 1.5px solid var(--line); background: var(--paper-alt);
color: var(--ink-soft); margin-bottom: 0.4rem; min-height: 1.4em;
}
.infographic-pyfilemode .result-box.ok-r { border-color: var(--ok); background: var(--ok-soft); color: var(--ok); }
.infographic-pyfilemode .result-box.err-r { border-color: var(--err); background: var(--err-soft); color: var(--err); }
@media (prefers-reduced-motion: reduce) {
.infographic-pyfilemode *, .infographic-pyfilemode *::before, .infographic-pyfilemode *::after {
animation-duration: 0.001ms !important; transition-duration: 0.001ms !important;
}
}
</style>
<div class="fm-wrap">
<h1>File Modes</h1>
<p class="fm-sub">open("notes.txt", mode) — the same file, seven very different outcomes.</p>
<div class="file-card">
<div class="file-bar">
<span>notes.txt</span>
<span class="file-status exists" id="fileStatus">exists</span>
</div>
<div class="file-body" id="fileBody">Hello
World</div>
</div>
<div class="file-ctl-row">
<button class="file-ctl-btn" id="resetFileBtn">↺ Reset file to "Hello / World"</button>
<button class="file-ctl-btn" id="deleteFileBtn">🗑 Delete notes.txt</button>
</div>
<div class="mode-grid" id="modeGrid"></div>
<p class="mode-desc" id="modeDesc"></p>
<div class="write-row" id="writeRow">
<span style="font-family:var(--mono-font); font-size:0.78rem; color:var(--ink-soft); align-self:center;">write:</span>
<input id="writeInput" type="text" value="New line!" />
</div>
<div class="run-row"><button class="run-btn" id="runBtn">Run: open("notes.txt", "r")</button></div>
<div class="result-box" id="resultBox">Pick a mode and hit Run.</div>
</div>
<script>
(function () {
var root = document.currentScript.closest('.infographic-pyfilemode')
|| document.querySelector('.infographic-pyfilemode');
var bodyAttr = document.body.getAttribute('data-darkmode');
var dark;
if (bodyAttr === 'true') { dark = true; }
else if (bodyAttr === 'false') { dark = false; }
else {
var match = document.cookie.match(/(?:^|;\s*)darkMode=([^;]+)/);
dark = match ? match[1] === 'true' : false;
}
if (dark) root.setAttribute('data-theme', 'dark');
var INITIAL_CONTENT = 'Hello\nWorld';
var fileExists = true;
var fileContent = INITIAL_CONTENT;
var fileBody = root.querySelector('#fileBody');
var fileStatus = root.querySelector('#fileStatus');
var modeGrid = root.querySelector('#modeGrid');
var modeDesc = root.querySelector('#modeDesc');
var writeRow = root.querySelector('#writeRow');
var writeInput = root.querySelector('#writeInput');
var runBtn = root.querySelector('#runBtn');
var resultBox = root.querySelector('#resultBox');
var modes = [
{ key: 'r', needsWrite: false, desc: 'Read only. File must already exist — errors if it\'s missing.' },
{ key: 'w', needsWrite: true, desc: 'Write only. Creates the file if missing — erases everything first if it already exists.' },
{ key: 'a', needsWrite: true, desc: 'Append only. Creates the file if missing — adds to the end without touching what\'s already there.' },
{ key: 'x', needsWrite: true, desc: 'Exclusive create. Only works if the file does NOT exist yet — errors if it does.' },
{ key: 'r+', needsWrite: true, desc: 'Read + write. File must exist. Writing overwrites from the very start, not the end.' },
{ key: 'w+', needsWrite: true, desc: 'Write + read. Same as w — erases everything first, then lets you read what you just wrote.' },
{ key: 'a+', needsWrite: true, desc: 'Append + read. Same as a — adds to the end, and you can read the whole file too.' }
];
var currentMode = 'r';
function renderFile() {
fileStatus.textContent = fileExists ? 'exists' : 'missing';
fileStatus.className = 'file-status ' + (fileExists ? 'exists' : 'missing');
if (fileExists) {
fileBody.textContent = fileContent;
fileBody.classList.remove('is-missing');
} else {
fileBody.textContent = '(no such file)';
fileBody.classList.add('is-missing');
}
}
function updateModeUI() {
var m = modes.filter(function (x) { return x.key === currentMode; })[0];
modeDesc.innerHTML = '<strong>"' + m.key + '"</strong> — ' + m.desc;
writeRow.style.display = m.needsWrite ? 'flex' : 'none';
runBtn.textContent = 'Run: open("notes.txt", "' + m.key + '")';
}
modes.forEach(function (m) {
var btn = document.createElement('button');
btn.className = 'mode-btn' + (m.key === currentMode ? ' is-selected' : '');
btn.textContent = m.key;
btn.addEventListener('click', function () {
root.querySelectorAll('.mode-btn').forEach(function (b) { b.classList.remove('is-selected'); });
btn.classList.add('is-selected');
currentMode = m.key;
updateModeUI();
resultBox.textContent = 'Pick a mode and hit Run.';
resultBox.className = 'result-box';
});
modeGrid.appendChild(btn);
});
root.querySelector('#resetFileBtn').addEventListener('click', function () {
fileExists = true;
fileContent = INITIAL_CONTENT;
renderFile();
});
root.querySelector('#deleteFileBtn').addEventListener('click', function () {
fileExists = false;
fileContent = '';
renderFile();
});
function setResult(text, kind) {
resultBox.textContent = text;
resultBox.className = 'result-box' + (kind ? ' ' + kind + '-r' : '');
}
runBtn.addEventListener('click', function () {
var writeVal = writeInput.value;
if (currentMode === 'r') {
if (!fileExists) {
setResult('FileNotFoundError: [Errno 2] No such file or directory: \'notes.txt\'', 'err');
return;
}
setResult('Opened for reading — file untouched.', 'ok');
return;
}
if (currentMode === 'x') {
if (fileExists) {
setResult('FileExistsError: [Errno 17] File exists: \'notes.txt\'', 'err');
return;
}
fileExists = true;
fileContent = writeVal;
renderFile();
fileBody.classList.add('flash-append');
setTimeout(function () { fileBody.classList.remove('flash-append'); }, 600);
setResult('Created notes.txt with your content.', 'ok');
return;
}
if (currentMode === 'w' || currentMode === 'w+') {
var erased = fileExists && fileContent.length > 0;
fileExists = true;
fileContent = writeVal;
renderFile();
fileBody.classList.add('flash-write');
setTimeout(function () { fileBody.classList.remove('flash-write'); }, 600);
setResult(erased ? 'Old content erased — file now contains only your new text.' : 'File created with your text.', erased ? 'err' : 'ok');
return;
}
if (currentMode === 'a' || currentMode === 'a+') {
fileExists = true;
fileContent = fileContent ? fileContent + '\n' + writeVal : writeVal;
renderFile();
fileBody.classList.add('flash-append');
setTimeout(function () { fileBody.classList.remove('flash-append'); }, 600);
setResult('Added to the end — nothing old was erased.', 'ok');
return;
}
if (currentMode === 'r+') {
if (!fileExists) {
setResult('FileNotFoundError: [Errno 2] No such file or directory: \'notes.txt\'', 'err');
return;
}
var overwritten = writeVal.length >= fileContent.length
? writeVal
: writeVal + fileContent.slice(writeVal.length);
fileContent = overwritten;
renderFile();
fileBody.classList.add('flash-write');
setTimeout(function () { fileBody.classList.remove('flash-write'); }, 600);
setResult('Overwrote from the beginning — anything past your new text\'s length stayed.', 'ok');
return;
}
});
renderFile();
updateModeUI();
})();
</script>
</div>🧪 Combining Modes
You can combine file modes like:
"rb"– Read binary"wb"– Write binary"ab"– Append binary"r+"– Read and write"w+"– Write and read (file overwritten)"a+"– Append and read