The mode string combines a primary mode — 'r' for reading, the default, which fails if the file doesn't exist; 'w' for writing, which creates the file if missing and truncates/overwrites it if it already exists; 'a' for appending, which creates the file if missing and always writes at the end; and 'x' for exclusive creation, which fails if the file already exists, useful for avoiding accidental overwrites — with an optional suffix, a 'b' for binary mode, returning/accepting bytes instead of str, or a '+' for allowing both reading and writing through the same file object.
1Understanding File Modes
The mode string combines a primary mode — 'r' for reading, the default, which fails if the file doesn't exist; 'w' for writing, which creates the file if missing and truncates/overwrites it if it already exists; 'a' for appending, which creates the file if missing and always writes at the end; and 'x' for exclusive creation, which fails if the file already exists, useful for avoiding accidental overwrites — with an optional suffix, a 'b' for binary mode, returning/accepting bytes instead of str, or a '+' for allowing both reading and writing through the same file object.
'w' mode silently truncates an existing file to zero length the instant you open it, even before you write anything — if you meant to add to an existing file instead of erasing it, you wanted 'a', not 'w'.
with open("draft.txt", "w") as f:
f.write("First version")
with open("draft.txt", "w") as f:
f.write("Overwritten")
with open("draft.txt", "r") as f:
print(f.read())2Practical Example
Here is a real-world application of File Modes showing how it is used in production Python code.
with open("log.txt", "w") as f:
f.write("Entry 1\n")
with open("log.txt", "a") as f:
f.write("Entry 2\n")
with open("log.txt", "r") as f:
print(f.read())3Best Practices
Follow these guidelines when working with File Modes:
1. Double check 'w' versus 'a' before opening a file you don't want to accidentally erase — 'w' truncates immediately on open
2. Use 'x' instead of 'w' when you specifically want the open() call to fail rather than silently overwrite an existing file
3. Use a 'b' suffix, like 'rb' or 'wb', for non-text data — images, audio, arbitrary binary formats — instead of trying to force it through text mode
Tip: 'w' mode silently truncates an existing file to zero length the instant you open it, even before you write anything — if you meant to add to an existing file instead of erasing it, you wanted 'a', not 'w'.
with open("draft.txt", "w") as f:
f.write("First version")
with open("draft.txt", "w") as f:
f.write("Overwritten")
with open("draft.txt", "r") as f:
print(f.read())