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() or pathlib 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.
Python File Operations

Python – Working with files

Python File Operations: Modes


Python File Operations: Writing a file

Python File Operations: CRUD
How Python file operations work
Every file operation follows the same three steps: open the file with open(path, mode), 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.
The with statement closes the file automatically, even if an exception is raised. Use it in all new code instead of calling f.close() by hand, as most of the gist code above does.
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("hello\n")
# f is closed here, and the data is flushed to diskCode language: PHP (php)
Always pass encoding="utf-8" when you open a file in text mode. Without it, Python uses the platform's default encoding, so the same script can read a file correctly on Linux and fail with UnicodeDecodeError on Windows.
File modes reference
| Mode | Meaning | If file exists | If file is missing |
|---|---|---|---|
r | Read (default) | Reads from the start | FileNotFoundError |
w | Write | Truncates it to zero length | Creates it |
a | Append | Writes go to the end | Creates it |
x | Exclusive create | FileExistsError | Creates it |
r+ | Read and write | Opens without truncating | FileNotFoundError |
w+ | Write and read | Truncates it | Creates it |
a+ | Append and read | Writes go to the end | Creates it |
b | Binary, combined with the above (for example rb, wb) | Works with bytes, no encoding | Same as the base mode |
t | Text (default), for example rt | Works with str | Same as the base mode |
Note: w never asks for confirmation. Opening an existing file in w mode wipes its contents immediately, even if you never call write(). Use x when you must not overwrite existing data.
Corrected CRUD example
The script below does the same create, read, update and delete steps as crud-file.py above. It runs cleanly from start to finish and can be run again without failing.
import os
os.makedirs("live", exist_ok=True) # make sure the folder exists
target = os.path.join("live", "createfile.txt")
# CREATE: 'x' refuses to overwrite an existing file
try:
with open(target, "x", encoding="utf-8") as f:
f.write("First line.\n")
except FileExistsError:
print(f"{target} already exists, skipping create")
# READ
with open(target, "r", encoding="utf-8") as f:
print(f.read())
# UPDATE (append): adds to the end
with open(target, "a", encoding="utf-8") as f:
f.write("Append this text.\n")
# UPDATE (overwrite): replaces everything
with open(target, "w", encoding="utf-8") as f:
f.write("Overwrite existing data.\n")
with open(target, encoding="utf-8") as f:
print(f.read())
# DELETE: safe because every handle is already closed
os.remove(target)
print("Exists after delete:", os.path.exists(target))Code language: PHP (php)
Expected output:
First line.
Overwrite existing data.
Exists after delete: FalseCode language: JavaScript (javascript)
The blank lines appear because each file ends with \n and print() adds a second newline. To print without the extra line, use print(f.read(), end="").
What was wrong in the original gist code
crud-file.pycallsos.remove()but never runsimport os, so the last line raisesNameError: name 'os' is not defined."D:\\myfiles\welcome.txt"contains\w, which is an invalid escape sequence. It happens to work, but recent Python versions emit aSyntaxWarning. Use a raw stringr"D:\myfiles\welcome.txt"or forward slashes"D:/myfiles/welcome.txt".open("myfile.txt", "x")fails withFileExistsErrorthe second time you run the script. The comment on the later"w"line says it creates a file "if it does not exist", but it also truncates an existing file.- Most files are opened and never closed. The last read of
live/createfile.txtleaves the handle open beforeos.remove(), which raisesPermissionErroron Windows. - The comment above the
demofile3.txtread says "after the appending". That file was overwritten withw, not appended to. f.flush()immediately beforef.close()does nothing extra, because closing a file always flushes it.live/createfile.txtneeds thelivefolder to exist. Modeacreates missing files but not missing directories.- In
input.py, the variableinputshadows Python's built-ininput()function, and the script carries on even when the existence check says the file is missing.
Reading files efficiently
f.read() 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:
with open("app.log", encoding="utf-8") as f:
for line in f: # streams line by line
if "ERROR" in line:
print(line.rstrip())
# Other options
with open("app.log", encoding="utf-8") as f:
first = f.readline() # one line, including the trailing \n
rest = f.readlines() # list of remaining lines (loads all into memory)
# Binary files such as images or archives
with open("logo.png", "rb") as f:
header = f.read(8) # returns bytesCode language: PHP (php)
Checking paths with os and pathlib
The example above uses os.getcwd(), os.listdir() and os.path.isfile(). The standard-library pathlib module does the same jobs with a cleaner, object-oriented API and handles path separators on every operating system:
from pathlib import Path
cwd = Path.cwd()
print("Files in", cwd, [p.name for p in cwd.iterdir()])
p = Path("live") / "myfile.txt" # / joins paths portably
print(p.exists(), p.is_file(), p.is_dir())
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("quick write\n", encoding="utf-8")
print(p.read_text(encoding="utf-8"))
p.unlink(missing_ok=True) # delete; no error if already goneCode language: PHP (php)
Note: Relative paths such as live/myfile.txt are resolved against the current working directory, not the script's folder. If a script works from your IDE but not from cron or CI, build paths from Path(__file__).resolve().parent instead.
Corrected JSON read and write example
This version of input.py stops if the input file is missing and avoids shadowing built-in names. It produces the same output.txt.
import json
from pathlib import Path
src = Path("sample-programs/system/input.json")
dst = src.with_name("output.txt")
if not src.is_file():
raise SystemExit(f"Input file not found: {src}")
with src.open("r", encoding="utf-8") as infile:
data = json.load(infile) # parse JSON into a dict
with dst.open("w", encoding="utf-8") as outfile:
outfile.write(f"{data['name']}'s Hobbies:\n")
for hobby in data["hobbies"]:
outfile.write(f"{hobby}\n")
# Writing JSON back out
with src.with_name("copy.json").open("w", encoding="utf-8") as f:
json.dump(data, f, indent=2)Code language: PHP (php)
Resulting output.txt for the sample input.json:
Jason's Hobbies:
music
programming
games
Common errors and fixes
| Error | Usual cause | Fix |
|---|---|---|
FileNotFoundError | Wrong relative path, or the parent folder is missing | Print os.getcwd(), use absolute paths, create folders with mkdir(parents=True, exist_ok=True) |
FileExistsError | Mode x on a file that already exists | Catch the exception or choose w/a deliberately |
PermissionError | No access rights, or the file is still open (Windows) | Close handles with with, check file ownership and permissions |
IsADirectoryError | The path points to a folder | Check with is_file() before opening |
io.UnsupportedOperation: not writable | Writing to a file opened with r | Open with w, a or r+ |
UnicodeDecodeError | File encoding differs from the default | Pass the correct encoding=, or open in rb for binary data |
Best practices
- Use
withfor every file you open. - Always set
encoding="utf-8"in text mode. - Prefer
pathlib.Pathover string concatenation for building paths. - Prefer trying the operation and catching
FileNotFoundErrorover checkingexists()first. Another process can delete the file between your check and youropen(). - For important files, write to a temporary file and then call
os.replace(tmp, final). The replace is atomic on the same filesystem, so readers never see a half-written file. - Do not name variables
input,file,openorlist, because doing so hides built-in names.
For more practice, see the Python tutorials. File handling also comes up often in Python interview questions.
Frequently asked questions
What is the difference between w and a mode in Python?
w truncates an existing file to empty before writing, and a keeps the existing content and adds new data at the end. Both create the file if it does not exist.
How do I check if a file exists in Python?
Use os.path.isfile(path) or Path(path).is_file() from pathlib. When you are about to open the file anyway, it is more reliable to open it directly and catch FileNotFoundError.
How do I delete a file in Python?
Call os.remove(path) or Path(path).unlink(). Close any open handles to the file first. Pass missing_ok=True to unlink() if a missing file should not raise an error.
Why should I use with open() instead of open() and close()?
The with block closes the file automatically, even if an exception happens partway through. That way buffered data is written and the handle is released.
What is the difference between r+ and w+?
Both allow reading and writing. r+ requires the file to exist and keeps its contents. w+ creates the file or truncates an existing one to empty.
Related tutorials
- More Python tutorials
- Top 50 Python Interview Questions and Answers
- TOP 100+ INTERVIEW QUESTIONS FOR PYTHON:-
- What is Pandas and use cases of Pandas?
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals